0

I am using python3 , flask server on ubuntu virtual machine. The server is working fine. It uploads a browsed video and print **found file when the browsed video file is in appropriate extension.

The problem is, every time when I restart my ubuntu virtual machine the IP address is changed and I have to update it manually in python script app.run(host= '192.168.1.101', debug=True).

Please tell me how to automatically update it.

Any help would be appreciated. Thanks in advance.

Here is the code.

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)
Afshan Anwarali
  • 337
  • 1
  • 3
  • 12

1 Answers1

0

you will have to either parse the "ip address" or "ifconfig" command, or use

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

cfr. Finding local IP addresses using Python's stdlib

Tohmaxxx
  • 423
  • 2
  • 9