【问题标题】:Auto-update Ubuntu IP address in python script在 python 脚本中自动更新 Ubuntu IP 地址
【发布时间】:2019-04-15 09:11:08
【问题描述】:

我在 ubuntu 虚拟机上使用 python3,flask 服务器。服务器工作正常。当浏览的视频文件具有适当的扩展名时,它会上传浏览的视频并打印**找到的文件。

问题是,每次我重新启动我的 ubuntu 虚拟机时,IP 地址都会更改,我必须在 python 脚本 app.run(host= '192.168.1.101', debug=True) 中手动更新它。

请告诉我如何自动更新。

任何帮助将不胜感激。 提前致谢。

这里是代码。

import os
from flask import Flask, request, redirect, url_for, send_from_directory, jsonify
from werkzeug import secure_filename

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'mp4'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
  # this has changed from the original example because the original did not work for me
    return filename[-3:].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    print("Printing the request {}".format(request.headers))
    print("Printing the request {}".format(request))
    print("Printing the request {}".format(request.data))
    print("Printing the request {}".format(request.form))
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            print('**found file', file.filename)
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            # for browser, add 'redirect' function on top of 'url_for'
            return jsonify({"success" : url_for('uploaded_file',
                                    filename=filename)})
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(host= '192.168.1.101', debug=True)

【问题讨论】:

    标签: python-3.x flask ubuntu-14.04


    【解决方案1】:

    你将不得不解析“ip地址”或“ifconfig”命令,或者使用

    import socket
    socket.gethostbyname(socket.gethostname())
    

    cfr。 Finding local IP addresses using Python's stdlib

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 2017-06-24
      • 2011-11-15
      • 2013-01-26
      • 2017-11-30
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多