Start a web server using Bottle and Flask (I also tried using Apache)

Introduction

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 usingbottle and Flask. It also describes how to connect ʻApache to a Python script.

environment

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. bottle1-api.png

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

About the code

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.

Embedding HTML files

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. bottle2-browser.png

About the code

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 ().

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

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. flask1-kwargs.png

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`. apache.png

important point

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. ** **

Recommended Posts

Start a web server using Bottle and Flask (I also tried using Apache)
I tried web scraping using python and selenium
Launch a web server with Python and Flask
I tried to create a sample to access Salesforce using Python and Bottle
I want to make a web application using React and Python flask
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I tried to get Web information using "Requests" and "lxml"
Creating a web application using Flask ②
Creating a web application using Flask ①
Creating a web application using Flask ④
I tried to make a todo application using bottle with python
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
I tried using Twitter api and Line api
I tried playing a ○ ✕ game using TensorFlow
I tried drawing a line using turtle
I tried using PyEZ and JSNAPy. Part 2: I tried using PyEZ
I tried to make a Web API
I tried using pipenv, so a memo
I tried benchmarking a web application framework
Build a CentOS Linux 8 environment with Docker and start Apache HTTP Server
I tried using PyEZ and JSNAPy. Part 1: Overview
[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
I tried object detection using Python and OpenCV
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server --2 PHP introduction
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server ―― 1. Apache introduction
I tried running Flask on Raspberry Pi 3 Model B + using Nginx and uWSGI
Create a web map using Python and GDAL
I tried using Pythonect, a dataflow programming language.
I tried reading a CSV file using Python
I tried using firebase for Django's cache server
Source compile Apache2.4 (httpd 2.4.43) + PHP7.4 on Linux and build a Web server ―― 1. Apache introduction
I tried using a database (sqlite3) with kivy
I tried to make a ○ ✕ game using TensorFlow
Source compile Apache2.4 (httpd 2.4.43) + PHP7.4 on Linux and build a Web server --2 PHP introduction
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
[Python + Bottle] I tried to release a web service that visualizes Twitter's positioned tweets.
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a web server --3. Use MySQL
I made a web application that maps IT event information with Vue and Flask
I tried using google test and CMake in C
I made a login / logout process using Python Bottle.
I tried hosting a Pytorch sample model using TorchServe
CTF beginner tried to build a problem server (web) [Problem]
I tried reading data from a file using Node.js.
I tried using Python (3) instead of a scientific calculator
Python: I tried a liar and an honest tribe
PyTorch Learning Note 2 (I tried using a pre-trained model)
HTTP server and HTTP client using Socket (+ web browser) --Python3
I tried to draw a configuration diagram using Diagrams
I tried using argparse
I tried using anytree
I tried using aiomysql
I tried using Summpy
I tried using coturn
I tried using "Anvil".
I tried using Hubot
I tried using ESPCN
I tried using PyCaret
I tried using cron
I tried using ngrok
I tried using face_recognition
Web application using Bottle (1)