Now that you've learned how to start a web server in Python, I'll post it for output. I hope it will be helpful to anyone.
In this article, we will not cover the standard libraries http
module and ʻurllibmodule, but explain based on the sample code using
bottle and
Flask. It also describes how to connect ʻApache
to a Python script.
WSGI When studying the Web with Python, the word WSGI is often used.
WSGI refers to a standardized API between a Python web application and a web server.
Many Python web frameworks and web servers use WSGI. It is said that there is not a high need for anyone other than framework and server developers to know how WSGI itself works.
All of the frameworks I'll cover use WSGI.
Bottle
Bottle is made from just one Python file, so it's very easy to try and deploy.
When I run the web server with the following code and access http: // localhost: 9999
with the GET method, it returns a response.
Let's install Bottle as a preparation.
$ pip install bottle
bottle1.py
from bottle import route, run
@route('/')
def myhome():
return "It's my home page"
run(host='localhost', port=9999)
$ python bottle1.py
Bottle v0.12.18 server starting up (using WSGIRefServer())...
Listening on http://localhost:9999/
Hit Ctrl-C to quit.
Go to http: // localhost: 9999
.
With status code 200, ʻIt's my home page` is displayed on the body, and you can see the contents of the response.
On the server side, the output is as follows.
127.0.0.1 - - [17/Dec/2019 08:30:39] "GET / HTTP/1.1" 200 17
Bottle uses the @ route
decorator to map the URL to the function that immediately follows it.
In this case, the /
is handled by the myhome ()
function. This time I received the request with the GET method,
You can specify @ route (method ='POST')
to receive requests from the POST method.
Run the web server with the run ()
function.
It's easy to implement like this, so it's useful for testing.
In the code above, I was creating the text in the code, You can also create an HTML file and view it in your browser.
First, prepare bottle2.py and index.html in the same folder.
Write index.html as follows.
index.html
It's my <b>new</b> home page
Write bottle2.py as follows.
bottle2.py
from bottle import route, run, static_file
@route('/')
def main():
return static_file('index.html', root='.')
run(host='localhost', port=9999)
Now start the server.
$ python bottle2.py
Access http: // localhost: 9999
with a browser.
By calling the static_file ()
function, you can return ʻindex.html of the current directory indicated by the argument
root` as a response.
There are various other functions.
For example
You can also add the following argument to run ()
.
debug = True
: A debug page is created when an HTTP error is returned. (Do not set on a web server that operates at home.)reloader = True
: The page reloads in the browser when you make changes to your Python code.You can also pass an argument to the URL and use the passed value. This can be achieved with the following code.
@route('/<thing>')
def main(thing):
return f'{thing}'
Developer site: https://bottlepy.org/docs/dev/
Flask
Flask is just as easy to use as Bottle.
First install.
pip install flask
Now, prepare flask1.py. As a requirement
/ sample / some
", let's display" some "in the browser with" some "as the argument value. /sample1?thing=hello&something=world
", let's embed the value specified in the query string in flask1.html
and display it.Here, the default directory for Flask static files is static
, so URLs for files in that directory also start with / static
.
flask1.py
from flask import Flask, render_template, request
app = Flask(__name__, static_folder='.', static_url_path='')
# http://localhost:9999/What to return when accessed by
@app.route('/')
def myhome():
return app.send_static_file('index.html')
@app.route('/sample/<thing>')
def echo(thing):
return thing
# sample1/Receive subsequent query strings as multiple arguments
@app.route('/sample1/')
def echo1():
kwargs = {}
kwargs['thing'] = request.args.get('thing')
kwargs['something'] = request.args.get('something')
return render_template('flask1.html', **kwargs)
app.run(host='localhost', port=9999, debug=True)
Next, create flak1.html.
Create a new folder called templates
. Save the following code under it.
flask1.html
<html>
<body>
It's my <b>new</b> home page
<br>{{ thing }}
<br>{{ something }}
</body>
</html>
After starting the server, if you access http: // localhost: 9999 / sample1 / $ thing = hello & something = world
with a browser, the following will be displayed.
Apache Next, let's use Apache HTTP Server to embed a Python script.
The most good WSGI module on the apache web server seems to be mod_wsgi
, so use this. (Quote: Getting Started Python3)
Reference mod_wsgi official document
This module can run Python code inside an Apache process or in a separate process that communicates with Apache.
If your OS is other than Windows, Apache is already included, but if you are using Windows, you have to Download.
I downloaded httpd-2.4.41-win64-VS16.zips
from Apache Lounge.
There is Apache24 in the downloaded file, so let's put it directly under c:
(not required)
There are two ways to use mod_wsgi
.
For more information https://pypi.org/project/mod-wsgi/
This time we will use pip
to install mod_wsgi
.
$ pip install mod_wsgi
Next, write a Python script.
Write it in wsgi.py
in an appropriate place as follows. (By the way, the location is c: /var/www/test/wsgi.py
)
wsgi.py
import bottle
application = bottle.default_app()
@bottle.route('/')
def home():
return "apache ok"
Then go to c: \ Apache24 \ bin
Enter the command mod_wsgi-express module-config
. This will allow you to see the location of the module. This information is required for the ʻApache` configuration described below.
c:\Apache24\bin>mod_wsgi-express module-config
LoadFile "c:/users/appdata/local/programs/python/python37/python37.dll"
LoadModule wsgi_module "c:/users/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd"
WSGIPythonHome "c:/users/appdata/local/programs/python/python37"
Next, add the following to the end of the C: \ Apache24 \ conf \ httpd.conf
file.
httpd.conf
LoadModule wsgi_module "c:/users/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd"
WSGIPythonHome "c:/users/appdata/local/programs/python/python37"
<VirtualHost *:80>
WSGIScriptAlias / c:/var/www/test/wsgi.py
<Directory "c:/var/www/test">
Require all granted
</Directory>
</VirtualHost>
Please change the description of LoadModule
and WSGIPythonHome
by referring to the output of mod_wsgi-express module-config
.
Let WSGIScriptAlias
find the relevant wsgi.py
.
Once you have done this, start apache. Start it with the command httpd -k start
in the working directory of C: \ Apache24 \ bin
.
If you access http: // localhost: 80
with your browser, you will see ʻapache ok as described in
wsgi.py`.
The source has been improved to the WSGI specification by ʻapplication = bottle.default_app (). Therefore, external connection is not possible unless the code has WSGI specifications. Also, if ʻapplication
is changed to ʻapp, it cannot be read. **
mod_wsgi looks for the ʻapplication
variable to bind the web server to the Python code. ** **