port management in python/flask application - python

I am writing a REST API using the micro framework Flask with python programming language. In the debug mode the application detect any change in source code and restart itself using the same host and port. In the production mode (no debug) the application does not restart it self when changing the source code so I have to restart the application by my self; the problem in this case is that the application cannot run using a port previously used in an old version the application, so I am asked to change the port with every app update:
This is how my code look like:
from flask import Flask, jsonify, request
import json
import os
app = Flask(__name__)
#app.route('/method1', methods=['GET'])
def method1():
return jsonify({"result":"true"})
#app.route('/method2', methods=['GET'])
def method2():
return jsonify({"result":"true"})
if __name__ == '__main__':
app.run(debug=True,port=15000)
How to solve this issue? or do I have to change port with every application update?

This code test.py doesn't change port that's specified in .run() args:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "123"
app.run(host="0.0.0.0", port=8080) # or host=127.0.0.1, depends on your needs
There is nothing that can force flask to bind to another TCP port in allowed range if you specified the desired port in run function. If this port is already used by another app - you will see
OSError: [Errno 98] Address already in use
after launching.
UPD: This is output from my pc if I run this code several time using python test.py command:
artem#artem:~/Development/$ python test.py
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
^Cartem#artem:~/Development$ python test.py
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
^Cartem#artem:~/Development/$ python test.py
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
^Cartem#artem:~/Development/$ python test.py
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Nov/2017 17:04:56] "GET / HTTP/1.1" 200 -
As you can see flask gets binded to 8080 port every time.
UPD2: when you will setup production env for your service - you won't need to take care of ports in flask code - you will just need to specify desired port in web server config that will work with your scripts through wsgi layer.

Related

Handling HTTPS post request in python flask

I have made a simple python flask program :
# save this as app.py
from flask import request
from flask import Flask
app = Flask(__name__)
#app.route("/", methods=['POST'])
def hello():
return "Hello, World!"
#app.route("/sms", methods=['POST'])
def sms():
print(request.get_json())
return "sms world"
if __name__ == '__main__':
app.run(port=443, host='0.0.0.0', ssl_context='adhoc')
This handles the HTTP post request. How can I make it handle HTTPS post requests?
When I execute the command flask run I get the following:
Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server
instead. * Debug mode: off * Running on http://127.0.0.1:5000/
(Press CTRL+C to quit)
So it still uses HTTP instead of https
pip install pyopenssl
When you run the script (or start with flask run if you prefer), you will notice that Flask indicates that it is running an https:// istance
first install pyopenssl with the command:
pip install pyopenssl
to launch it in https just add the parameter: ssl_context='adhoc'
if __name__ == '__main__':
app.run(port=443, host='0.0.0.0', ssl_context='adhoc')
Once started the following message will be shown:
* Serving Flask app 'test' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on https://192.168.0.62:443/ (Press CTRL+C to quit)
Obviously then once the application goes into production this parameter will no longer be needed, but you will have to set your wsgi to communicate in https
You can try ngrok, it is a useful tool to deploy an HTTPS and HTTP service from local to public net.
https://ngrok.com/

Flask auto-reload functionality not working with Pycharm Remote Deployment

It's hard to remember when, but at one point the auto-reload function of Flask started to not work anymore in my project.
This is the output upon starting my app :
FLASK_APP = back/python/app/app.py:app
FLASK_ENV = development
FLASK_DEBUG = 1
In folder C:/path/to/project
ssh://[VirtualMachineIP]:22/root/env/bin/python3.7 -u -m flask run -h 0.0.0.0 -p 1234
* Serving Flask app 'back/python/app/app.py:app' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://[VirtualMachineIP]:1234/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 106-048-128
The development environment and Debug mode are both on. Thus, upon saving changes in a file (while the app is deployed) I get the usual message :
* Detected change in '/path/to/changed/file.py', reloading
Signaling that the app is reloading with the new code. Except it doesn't reload anything, and the message doesn't appear on any further changes until I'm forced to restart the app.
PyCharms runs on Windows and communicates via ssh to my Virtual Machine, where the code is executed. I have installed the following modules:
flask
flask-socketio
eventlet
flask-cors
Any help is welcomed. Thanks :)
The FLASK_DEBUG environment variable is badly supported, it may not behave as expected if set in code. (Quoted from the source of flask).
It suggest to use flask run in debug mode.
eg: $ flask --app hello --debug run
If it still not work, you can force to use reloader like this:
if __name__ == '__main__':
app.run(host=config.HOST, port=config.PORT, debug=True)
Take care, the app.run() must be wrapped with if __name__ == '__main__'.
doc: https://flask.palletsprojects.com/en/2.2.x/config/#DEBUG

Flask app: The website cannot be reached 127.0.0.1 has refused the connection

I have written a simple flask app:
from flask import Flask,request
import pandas as pd
import numpy as np
import pickle
app=Flask(__name__)
pickle_in=open('classifier_new.pkl','rb')
classifier=pickle.load(pickle_in)
def welcome():
return "Welcome All"
if __name__=='__main__':
app.run()
The console tells me:
* Serving Flask app "bankAuth_app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
But when I try to visit the http://127.0.0.1:5000/ I get:
The website cannot be reached
127.0.0.1 has refused the connection.
Try the following:
Check connection
Check proxy and firewall
What can I do here? I am not using a proxy and I do not know why the firewall should be responsible here...

Python run command to launch server then continue my main program

I want to use command to launch server in python code, but main program stop here.
How to modify code to let server launch then continue my main program code.
This is my python code below.
import os
os.system('/usr/local/bin/python3.7 -m pyxtermjs')
print("Hello")
This is my console output below
serving on http://127.0.0.1:5000
* Serving Flask app "pyxtermjs.app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance.
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
You can use a Thread to multiprocess:
import os
from threading import Thread
def pro(): # Define a function to add to the Thread
os.system('/usr/local/bin/python3.7 -m pyxtermjs')
program = Thread(target=pro) # Define the Thread with the function
program.start() # Start the Thread
print('Hello World')
You should use subprocess.popen, like advised here
subprocess.Popen(["/usr/local/bin/python3.7", "-m", "pyxtermjs"])

Flask returning 505 “Broken Pipe” on Abyss Web Server

I have written a simple script which I am trying to "deploy" on the Abyss Web Server. I have followed the instructions on Aprelium website. However when I try and access the 'app' a 500 (internal server error) is returned.
The error was logged by the server:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[14/Nov/2017:19:44:12 +0000] CGI: [(path)\dev\Python\Scripts\python.exe yourapplication.py ] URI: /dev/Python/yourapplication.py Broken pipe
I also tried following the instructions on the Flask Site however these instructions relate to Linux and they document using command line so I am not even sure I was using WSGI or CGI correctly.
This is my script if it helps:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
app.run()
How do I fix this?

Categories

Resources