As wfastcgi module is not compatible with Python 3.7, What is the best way to host a python flask application on a Windows Server?
you need to install the python,wfastcgi, and flask at your server.
You can download the python from below link:
https://www.python.org/downloads/
after installing python download the wfastcgi:
pip install wfastcgi
run the command prompt as administrator and run this command.
wfastcgi-enable
run this command to enable wfastcgi.
below is my flask example:
app.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello from FastCGI via IIS!"
if __name__ == "__main__":
app.run()
after creating an application to run it use below command:
python app.py
now enable the cgi feature of iis:
now open iis.
right-click on the server name and select add site.
enter the site name physical path and the site binding.
after adding site select the site name and select the handler mapping feature from the middle pane.
Click “Add Module Mapping”
add below value:
executable path value:
C:\Python37-32\python.exe|C:\Python37-32\Lib\site-packages\wfastcgi.py
Click “Request Restrictions”. Make sure “Invoke handler only if
request is mapped to:” checkbox is unchecked:
Click “Yes” here:
now go back and again select the server name and select fast CGI setting from the middle pane.
Double click it, then click the “…” for the Environment Variables
collection to launch the EnvironmentVariables Collection Editor:
Set the PYTHONPATH variable:
And the WSGI_HANDLER (my Flask app is named app.py so the value is
app.app — if yours is named site.py it would be site.app or similar):
Click OK and browse to your site:
Note: Do not forget to assign the iusr and iis_iusrs user permission to the flask site folder and python folder.
Related
After spending many hours reading dozens of guides, I finally got into a working setup, and decided to publish the instructions here.
The problem: I have a working flask app running in my machine. How do I launch it as a web app using Microsoft Azure platform?
So here is my guide. I hope it will help others!
Steps for launching a new web app under Azure:
0. Login to Azure
Goto Azure portal https://portal.azure.com/ and sign-in using your Microsoft account.
1. Create a resource group:
Home > create a resource > Resource group
fill in: subscription(Free Trial), name (something with _resgrp), Region (e.g. West Europe)
2. DB:
Home > create a resource > create Azure Cosmos DB > Azure Cosmos DB for MongoDB
fill in: subscription(Free Trial), resource group (see above), account name (something with _db), Region (West Europe), [create]
goto Home > db account > connection strings, copy line marked "PRIMARY CONNECTION STRING" and keep it aside.
3. App:
Home > create a resource > create Web App
fill in: subscription(Free Trial), resource group (see above), name (will appear in the site url!),
publish: code, run time stack: python 3.9, region: West Europe, plan: Basic B1 ($13/mon), [create]
Home > our-web-app > configuration > Application settings > Connection strings
click "New Connection strings" and set MYDB with the connection string from step 2.
4. Code:
We will use a nice "to-do list" minimalist app published by Prashant Shahi. Thank you Prashant!
Clone code from https://github.com/prashant-shahi/ToDo-List-using-Flask-and-MongoDB into some local folder.
Delete everything but app.py, static, templates, requirements.txt
Edit requirements.txt so that Flask appears without "==version", because an older version is there by default.
create wsgi.py with:
from app import app
if __name__ == '__main__':
app.run()
Create go.sh with the following code. These commands are will setup the environment and then start gunicorn to respond to web requests. Some of these commands are used for debug only.
# azure webapp: called under sh from /opt/startup/startup.sh
set -x
ls -la
pip install -r /home/site/wwwroot/requirements.txt
echo "$(pwd) $(date)"
ps aux
gunicorn --bind=0.0.0.0 --log-level=debug --timeout 600 wsgi:app
edit app.py:
replace first 3 lines about db connection with: (btw, MYDB comes from steps 3)
CON_STR = os.environ['CUSTOMCONNSTR_MYDB']
client = MongoClient(CON_STR) #Configure the connection to the database
after app = Flask(name) add these lines for logging:
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
add first line under def about(): #clicking [about] in the app will dump environment vars to the logs)
app.logger.debug('\n'.join([f'{k}={os.environ[k]}' for k in os.environ.keys()]))
5. Ftp:
Home > our-web-app > Deployment Center > FTPS Ceredentials
Open FileZilla, top-left icon, [new site]
copy paste from web to FileZilla: FTPS endpoint into host, user to username, password to password, [connect]
upload the content (not the parent!) of the folder from step 4 to the remote path /site/wwwroot
6. Launch:
Home > our-web-app > configuration > General settings > Startup Command
paste this: sh -c "cp go.sh go_.sh && . go_.sh"
7. Test:
Browse to https://[our-web-app].azurewebsites.net
8. Logging / debugging:
Install Azure CLI (command line interface) from https://learn.microsoft.com/en-us/cli/azure/install-azure-cli
Open cmd and run
az login
# turn on container logging (run once):
az webapp log config --name [our-web-app] --resource-group [our-step1-group] --docker-container-logging filesystem
# tail the logs:
az webapp log tail --name [our-web-app] --resource-group [our-step1-group]
9. Kudu SCM management for the app
(must be logged into Azure for these to work):
Show file/dir: https://[our-web-app].scm.azurewebsites.net/api/vfs/site/[path]
Downloads full site: https://[our-web-app].scm.azurewebsites.net/api/zip/site/wwwroot
Status: https://[our-web-app].scm.azurewebsites.net/Env
SSH: https://[our-web-app].scm.azurewebsites.net/webssh/host
Bash: https://[our-web-app].scm.azurewebsites.net/DebugConsole
More on REST API here: https://github.com/projectkudu/kudu/wiki/REST-API
10. Notes:
I don't recommend on using automatic deployment from GitHub / BitBucket, unless you have Azure's support available. We encountered many difficulties with that.
Any comments are most welcome.
I want to know the correct way to start a flask application. The docs show two different commands:
$ flask -a sample run
and
$ python3.4 sample.py
produce the same result and run the application correctly.
What is the difference between the two and which should be used to run a Flask application?
The flask command is a CLI for interacting with Flask apps. The docs describe how to use CLI commands and add custom commands. The flask run command is the preferred way to start the development server.
Never use this command to deploy publicly, use a production WSGI server such as Gunicorn, uWSGI, Waitress, or mod_wsgi.
As of Flask 2.2, use the --app option to point the command at your app. It can point to an import name or file name. It will automatically detect an app instance or an app factory called create_app. Use the --debug option to run in debug mode with the debugger and reloader.
$ flask --app sample --debug run
Prior to Flask 2.2, the FLASK_APP and FLASK_ENV=development environment variables were used instead. FLASK_APP and FLASK_DEBUG=1 can still be used in place of the CLI options above.
$ export FLASK_APP=sample
$ export FLASK_ENV=development
$ flask run
On Windows CMD, use set instead of export.
> set FLASK_APP=sample
For PowerShell, use $env:.
> $env:FLASK_APP = "sample"
The python sample.py command runs a Python file and sets __name__ == "__main__". If the main block calls app.run(), it will run the development server. If you use an app factory, you could also instantiate an app instance at this point.
if __name__ == "__main__":
app = create_app()
app.run(debug=True)
Both these commands ultimately start the Werkzeug development server, which as the name implies starts a simple HTTP server that should only be used during development. You should prefer using the flask run command over the app.run().
Latest documentation has the following example assuming you want to run hello.py(using .py file extension is optional):
Unix, Linux, macOS, etc.:
$ export FLASK_APP=hello
$ flask run
Windows:
> set FLASK_APP=hello
> flask run
you just need to run this command
python app.py
(app.py is your desire flask file)
but make sure your .py file has the following flask settings(related to port and host)
from flask import Flask, request
from flask_restful import Resource, Api
import sys
import os
app = Flask(__name__)
api = Api(app)
port = 5100
if sys.argv.__len__() > 1:
port = sys.argv[1]
print("Api running on port : {} ".format(port))
class topic_tags(Resource):
def get(self):
return {'hello': 'world world'}
api.add_resource(topic_tags, '/')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=port)
The very simples automatic way without exporting anything is using python app.py see the example here
from flask import (
Flask,
jsonify
)
# Function that create the app
def create_app(test_config=None ):
# create and configure the app
app = Flask(__name__)
# Simple route
#app.route('/')
def hello_world():
return jsonify({
"status": "success",
"message": "Hello World!"
})
return app # do not forget to return the app
APP = create_app()
if __name__ == '__main__':
# APP.run(host='0.0.0.0', port=5000, debug=True)
APP.run(debug=True)
For Linux/Unix/MacOS :-
export FLASK_APP = sample.py
flask run
For Windows :-
python sample.py
OR
set FLASK_APP = sample.py
flask run
You can also run a flask application this way while being explicit about activating the DEBUG mode.
FLASK_APP=app.py FLASK_DEBUG=true flask run
I'm trying to deploy my Django app I've split the settings.py and put in a settings folder. Now before I run my server, I must first this
set DJANGO_SETTINGS_MODULE=src.settings.dev
How can I make the above command to be automatic so I don't have type it every time before running the server .thanks
edit the below line in your manage.py for example in my case was
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings.dev')
The scenario is below:
I SSH to server Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-96-generic
x86_64) using putty with my credentials, from Windows
Go to the directory where I put my source code
start Flask app by running command python3 main.py logs are showing on terminal
however, after I left my computer for some time the session is disconnected/ended.
I know the app still running because another team still can test the app
when I re-login to the server and go to the same directory I don't want to kill/restart the already running app because it would interfere with others doing the test
How to see the running log so I would know what testers are doing and occasionally catch what's wrong
my main.py code:
if __name__ == "__main__":
ip = 'someip'
port = 9053
app.run(debug=True, host=os.getenv('IP', ip),
port=int(os.getenv('PORT', port)), threaded=True)
you can save your python log on file, so you can review it any time, this the example of using logging lib:
import logging
logger = logging.getLogger(<logging_name>)
fh = logging.FileHandler(<logging file>)
logger.addHandler(fh)
I have deployed a simple Flask application on an azure webapp by forking the repo from https://github.com/Azure-Samples/python-docs-hello-world
Here is my application.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
#app.route("/sms")
def hello_sms():
return "Hello World SMS!"
# if __name__ == '__main__':
# app.run(debug = True)
And this is my requirements.txt
click==6.7
Flask==1.0.2
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
Werkzeug==0.14.1
At first when I opened the URL ( https://staysafe.azurewebsites.net/ ) i got this message, "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
After which i when to the application settings in the webapp dashboard in azure and set a python version.
And ever since this is what I get when i open my URL
Any clue as to what is going wrong?
Seams that your code is not uploaded to portal.
Please follow this official document for your test.
I Used your code from https://github.com/Azure-Samples/python-docs-hello-world, and works fine. The steps as below:
Environment: python3.7, windows 10
1.Open git bash,download the code to local using git clone https://github.com/Azure-Samples/python-docs-hello-world.git
2.In git bash, execute cd python-docs-hello-world
3.In git bash, execute following command one by one:
py -3 -m venv venv
venv/scripts/activate
pip install -r requirements.txt
FLASK_APP=application.py flask run
4.Open a web browser, and navigate to the sample app at http://localhost:5000/ .
It is to make sure it can work well in local.
5.Then just follow the article to create deployment credetial / resource group / service plan / a web app
6.If no issues, in git bash, push the code to azure:
git remote add azure <deploymentLocalGitUrl-from-create-step>
Then execute git push azure master
7.Browse to the website like https://your_app_name.azurewebsites.net, or https://your_app_name.azurewebsites.net/sms,
it works fine, screenshot as below: