How to run Python (Flask) Server in Background? [duplicate] - python

This question already has answers here:
How to host Python 3.7 flask application on Windows Server?
(1 answer)
Are a WSGI server and HTTP server required to serve a Flask app?
(3 answers)
Serving Flask app with waitress on windows
(8 answers)
Closed 1 year ago.
I want to run a local server which executes as specific script when a GET request to the IP is made,
because of that I need to run the server in the background (while a other script is runing too) without printing any stuff.
Here is my Code:
from flask import Flask
app = Flask(__name__)
#app.route('/', methods = ['GET'])
def index():
return "Hello How are you?"
if __name__ == '__main__':
app.run(port = 5000)
I tried it with Threading but I always get stuck at this Output
When running this code I get this Output:
* 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://IP:5000/ (Press CTRL+C to quit)```

You could use pythonw to run the application in the background:
pythonw -m flask run > log.txt 2>&1
make sure the name of the Python file is app.py.

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.

Trying to run flask with the following code [duplicate]

This question already has answers here:
Warning message while running Flask
(12 answers)
Closed 2 years ago.
from flask import Flask
app = Flask(_name_)
#app.route('/')
def index():
return '<h1>Hello, world</h1>'
I get this error
* Serving Flask app "application.py"
* 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
This is just a warning as flask server is not meant for production.
You can use
export FLASK_ENV=development
before flask run
It depends if you are running it from command line or adding python code to run it.
If you want to run it with Python, add this to the bottom of your code.
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
(you can change the port number, to access it on a browser, type: 127.0.0.1:80)
If you are running it from command line, you run
flask run
Note this appears every time:
Serving Flask app "application.py" * 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
All it tells you is that this server is only used for development or production. Hosting it for commercial/public use would require additional files and web hosting.
You can allow debugging to be on with
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, DEBUG=True)
OR
export FLASK_ENV=development (linux/macos)
set FLASK_ENV=development (Windows)
Hope this helps (follow me on GitHub #haydenso)

Python import from a virtual environment when run in apache

I am new in python. I am trying to deploy python code on apache server for i.e i have created flask api. So for apache i have installed XAMPP and changed my httpd.conf to execute python on apache. It works well!! Here is code example which is working
Code working:
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
print("Content-type: text/html\n")
print ("Hello Python Web Browser!! This is cool!!")
But when I tried to import that through 500 Error, Here is the code
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'testing'
if __name__ == '__main__':
app.run(debug = True)
flask is installed on my environment (myproject). When I run through command like python test.py and it works.
Flask has it's own development web server.
Using python myfile.py which will work properly as a webserver (no need for apache on development).
If you still want do deploy on Apache, Flask have some info on how to do so, docs: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/
Special attention to this: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/#creating-a-wsgi-file

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.

Whats the difference between ./webapp.py and python webapp.py [duplicate]

This question already has answers here:
Getting Python error "from: can't read /var/mail/Bio"
(6 answers)
Closed 9 months ago.
I have started with python n flask few days ago. I was just trying to run a python file webapp.py on a terminal with following code but got errors:
$ ./webapp.py
from: can't read /var/mail/flask
from: can't read /var/mail/flask
./webapp.py: line 3: syntax error near unexpected token `('
./webapp.py: line 3: `app = Flask(__name__)'
But it runs successfully with the command:
$ python webapp.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
webapp.py
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
As a part of curiosity,
Whats the difference between ./webapp.py and python webapp.py?
When running a python script directly (without specifying the interpreter in the command), you need to tell the shell which interpreter will process the script, e.g.:
#!/usr/bin/env python
from flask import Flask
from flask import render_template
This first line is often referred to as "shebang".

Categories

Resources