在python脚本中自动更新Ubuntu IP地址

时间:2018-11-12 15:52:50

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

我正在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)

1 个答案:

答案 0 :(得分:0)

您将不得不解析“ ip address”或“ ifconfig”命令,或使用

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

cfr。 Finding local IP addresses using Python's stdlib