How To Set Up Python Web Application Development Environment

1. Make sure that the Python version of the system installation is 3.6.x.

$ python3 --version
Python 3.6.1

2. Run pip3 command to install the third-party libraries you need to develop your web application.

2.1 Install the asynchronous framework aiohttp

$ pip3 install aiohttp

2.2 Install front end template engine jinja2.

$ pip3 install jinja

2.3 Install MySQL Python driver.

  1. Download and install MySQL server from MySQL official website, after installation, be sure to remember the root password.
  2. Install MySQL Python asynchronous driver aiomysql.
    $ pip3 install aiomysq

3. Create Python Web Application.

3.1 Create web app project folder structure.

-webapp/ <-- root folder
|
+- backup/ <-- backup folder
|
+- conf/ <-- configure folder
|
+- dist/ <-- package folder
|
+- www/ <-- web folder,store .py source file
| |
| +- static/ <-- store static files like css, image and javascript.
| |
| +- templates/ <-- store template files
|
+- ios/ <-- store iOS app source files
|
+- LICENSE <-- project LICENSE

After creating the catalog structure of the project, it is suggested to build a git repository and synchronize it to GitHub to ensure the security of code modification. We will write git tutorial articles later to tell you how to do it.

3.2 Write web app skeleton.

Because our python web app is based on asyncio, so we use aiohttp to write a basic app.py file as below.

import logging; logging.basicConfig(level=logging.INFO)

import asyncio, os, json, time
        from datetime import datetime

from aiohttp import web

def index(request):
        return web.Response(body=b'<h1>Hello World</h1>')

@asyncio.coroutine
def init(loop):
        app = web.Application(loop=loop)
        app.router.add_route('GET', '/', index)
        srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 9000)
        logging.info('server started at http://127.0.0.1:9000...')
        return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

Run python app.py in command line, and the python web app will listen for http request on port 9000 and respond to the home page /.

$ python3 app.py
INFO:root:server started at http://127.0.0.1:9000..

Here we simply return a string ‘Hello World’, which you can see in the browser. This means that our web app skeleton is already built and we can add more things into it.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.