Python run command to launch server then continue my main program - python

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"])

Related

Running Flask by "flask run" vs running from editor (Windows 10)

If I run my Flask app through the command "flask run", not only the arguments in app.run are ignored (making debugger false and choosing the default port 5000), but changes made to the script too, e.g. changing url_prefix to "/views". The cmd prompt won't even respond when I save the script after making alterations. This way, changes are only effective after stopping the script then running again.
This doesn't happen when the app script is ran through VSCode commands (Ctrl+F5 or the play button): through those, the script is executed as written and changes are recognized right after saving a script.
Why is that so?
from flask import Flask
from views import views
app = Flask(__name__)
app.register_blueprint(views, url_prefix="/")
if __name__ == '__main__':
app.run(debug=True, port=8000)
C:\Users\*******\Documents\flask_quick_website>flask run
* 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)
The flask executable works by importing the app object from your code. This is similar to how a WSGI server like gunicorn works (research what this is if you're unsure).
As for when you run the script with VSCode, or in-fact if you launch with the python executable by running python app.py or similar, then anything inside the if __name__ == '__main__': block is executed, in your case the app.run call.
Also note your app.run call is passed the debug=True argument. If you investigate the Flask source code, inside the run function, the use_reloader argument is set to the same value as debug so in this case the auto-reloader runs if debug is True.
So how to make the auto-reloader work with the flask command? Pass the --reload flag:
flask run --reload
You can also set the environment to development to achieve the same. On windows:
> set FLASK_ENV=development
> flask run
See Environment and Debug features for more on this.

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

CTRL+C does not terminate aiohttp app in Python 3.6 script on Windows

A simple Python 3.6 script using aiohttp and python-socketio and running on Windows 10 outputs the following when started:
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
However, pressing CTRL+C does not terminate the script! I had to open Task Manager and kill each of the Python processes until killing one of them releases the aiohttp script back to the command prompt.
Any one experienced the same problem?
from aiohttp import web
import socketio
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
#sio.on('connect')
def connect(sid, environ):
print(sid)
if __name__ == '__main__':
web.run_app(app)

port management in python/flask application

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.

Categories

Resources