Explosive speed with Python (Bottle)! Web API development

Overview

When developing a certain web application, it became necessary to call the Web API of another server. It is a memo that a simple Web API was built at explosive speed because a pseudo environment is required at the time of development.

environment

Python installation

Download the installer from the following site and start the installer https://www.python.jp/install/windows/install_py3.html

Check the options at the time of installation, such as "Install for all users" and "Add path to environment variables". (If you do not check it, it will be installed in the folder of the logged-on user of the OS, and you will have to set the environment variables yourself.)

When the installer is complete, at the command prompt

python --version

Installation is complete when the version comes out.

Installation of required packages

Then, execute the following commands at the command prompt (execute with administrator privileges).

Install Bottle

pip install bottle

DB used PostgreSQL. Use pycopg2 for DB connection.

pip install psycopg2

Hello World

Make sure it works. Create index.py and edit it as follows.

index.py


from bottle import route, run, template 
 
@route('/hello/<name>')
def index(name):
  return template('<b>Hello {{name}} </b>!', name=name)
 
run(host='localhost', port=8080)

That's it ... isn't it?

Run python index.py at the command prompt to start it on localhost. And when you access http: // localhost: 8080 / hello / tsumasakky with your browser Hello tsumasakky! Is displayed on the screen and it is successful.

Web server construction

Apache installation

https://www.apachelounge.com/download/VC15/ Download from around here.

Copy the unzipped "Apache24" directly under C on the server

WSGI setup

Download the file from the following site https://www.lfd.uci.edu/~gohlke/pythonlibs/#mod_wsgi

Although it is a file name

Apache 2.4 VC "15" Python"37" Windows "64"bit

So, "mod_wsgi-4.6.8 + ap24vc15-cp37-cp37m-win_amd64.whl" I downloaded. Please download according to your environment.

Install at the command prompt. (Specify the location of the downloaded file)

pip insatll mod_wsgi-4.6.8+ap24vc15-cp37-cp37m-win_amd64.whl

Editing httpd.conf

First, execute the following command at the command prompt to get the mod_wsgi settings.

mod_wsgi-express module-config

Then, it will be displayed as follows.

LoadFile "c:/program files/python37/python37.dll"  
LoadModule wsgi_module "c:/program files/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd"  
WSGIPythonHome "c:/program files/python37"  

Copy the displayed settings and add them to Apache's httpd.conf. (Around the end of the Load Module) In addition, add the routing to the adapter to be created later.

httpd.conf


WSGIScriptAlias /api C:\Apache24\htdocs\adapter.wsgi

Creating an adapter

Create an adapter.wsgi file in the path set in WSGIScriptAlias to see if the wsgi settings are working.

adapter.wsgi


def application(environ,start_response):
    status = '200 OK'
    output = b'Hello World!'
    response_headers = [('Content-type','text/plain'),
                        ('Content-Length',str(len(output)))]
    start_response(status,response_headers)
    return [output]

Restart Apache and go to http: // localhost / api. If "Hello World" comes out, it's a success!

Launch your own app via the adapter

Edit ʻindex.py and ʻadapter.wsgi earlier.

adapter.wsgi


import sys, os
dirpath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(dirpath)
os.chdir(dirpath)
import bottle
import index
application = bottle.default_app()

index.py


from bottle import route, run, template
from bottle import TEMPLATE_PATH
import psycopg2

@route('/hello')
def hello():
    return template('<b>Hello World!</b>',)

@route('/users')
def users():
    conn = psycopg2.connect("postgresql://postgres:postgres@localhost:5432/sample")
    cur = conn.cursor()
    cur.execute('select * from sample.users;')
    users = cur.fetchall()
    cur.close()
    conn.close()
    return template('<b>{{users}}</b>!', users=users)
 
if __name__ == '__main__':
    run(host='localhost', port=8080, debug=True, reloader=True)

When I restarted Apache and accessed http: // localhost / api / users, I was able to get the list of users from the DB.

Impressions

Although it took some time to build the server, the actual application coding was completed in about 10 minutes! It's super detonation velocity!

By the way, after this, pycopg2 gets the data from the DB in dictionary type, converts it to dict-> json and returns it ~ I built the API with such a correspondence.

You can't do it the above way, or you can do this! Please comment if you like!

Until the end Thank you for reading. (m´ ・ ω ・ `) m

reference

Recommended Posts

Explosive speed with Python (Bottle)! Web API development
Web API with Python + Falcon
[Web development with Python] query is also redirect
Hit a method of a class instance with the Python Bottle Web API
[Web development with Python] Precautions when saving cookies
Calculate Gaussian kernel at explosive speed even with python
Use Trello API with python
Web scraping with python + JupyterLab
BASIC authentication with Python bottle
EXE Web API by Python
Use Twitter API with Python
Web application development with Flask
Play RocketChat with API / Python
Call the API with python3.
Web application with Python + Flask ② ③
Use subsonic API with python3
Web scraping beginner with python
Streamline web search with python
Web application with Python + Flask ④
Build a web API server at explosive speed using hug
[Ipdb] Web development beginners tried to summarize debugging with Python
Explosive speed! Using Python Simple HTTP Server for kintone development
[SAP CP] Web API created with python in CF environment
Build a speed of light web API server with Falcon
Web application with Python3.3.1 + Bottle (1) --Change template engine to jinja2
Create Awaitable with Python / C API
Web scraping with Python ① (Scraping prior knowledge)
Get reviews with python googlemap api
Implemented file download with Python + Bottle
Run Rotrics DexArm with python API
Web application development memo in python
Getting Started with Python Web Applications
Web scraping with Python First step
I tried web scraping with python.
Monitor Python web apps with Prometheus
Quine Post with Qiita API (Python)
Get web screen capture with python
Hit the Etherpad-lite API with Python
Othello game development made with Python
[python] Read information with Redmine API
Hit the web API in Python
Roughly speed up Python with numba
Prepare Python development environment with Atom
Application development with Docker + Python + Flask
Rubyist tried to make a simple API with Python + bottle + MySQL
[Web development with Python] Measures against garbled characters when outputting html
Get US stock price from Python with Web API with Raspberry Pi
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
Collecting information from Twitter with Python (Twitter API)
[Python] Web application from 0! Hands-on (3) -API implementation-
Automatically create Python API documentation with Sphinx
WEB scraping with Python (for personal notes)
[Development environment] Python with Xcode [With screen transition]
Simple Slack API client made with Python
Retrieving food data with Amazon API (Python)
Python: Reading JSON data from web API
Getting Started with Python Web Scraping Practice
Daemonize a Python web app with Supervisor
Development and deployment of REST API in Python using Falcon Web Framework
[Personal note] Web page scraping with python3
Download files on the web with Python