Write Web programs using Python3

Python can write web applications? ? ? Yes, you heard wrong, but this article is not to teach you to write "web application" but to teach you how to program Python-based server. Nonsense is not how much we should quickly begin!

Introduction & Installation

First enclose webpy URL

WebPy official website: http://webpy.org

The official version given Python support

Python2.7,Python > 3.5

Installation steps, starting with the official website to download the package, and then drag the directory you like, such as: C: \ Windows \ System32 \

Then run the following command

# For Python 2.7
pip2 install web.py==0.40

# For Python 3
python3 -m pip install web.py==0.40

The authors look at github can go Stttttttar: https://github.com/webpy/webpy/releases
Of course, if you want to uninstall, then run the following command
the unzip webpy-0.40.zip
cd webpy-0.40 /
python3 setup.py

Mavericks try knife

First we create a working directory, and then create two files (index.html with server.py)

Server.py first to make a little deal, First we import the web module

import web

According to the official documentation, we would like to inform web url module type, that is, to construct a url

urls = (
  '/', 'index'
)

The first part is a regular expression matching URL, as /, / index / hello, / item / (\ d +), and the like (i.e., \ d + matched sequence numbers). Brackets indicate matching data capture, for later use. The second part is a class name, to send a request to, for example, index, view, welcomes.hello (wherein obtaining hello class welcomes module), or get_ \ 1. \ 1 Replace your regular expression first capture; capture any remaining will be passed to your function. This line says we want URL / (ie home) by a process called class index.

Then we want to simulate a request to the server

class index:
   def GET(self):
   return "Hello PyWeb!"

When someone GETrequests /when this GETfunction will be invoked at any time web.py.

Well, we just need to limit it finished the last sentence. This line will tell web.py began offering web page:

if __name__ == "__main__":
app = web.application(urls, globals())
app.run()

If all goes well we will together draw the following code above the code

import web #导入模块
urls = (
'/', 'index'
)
class index:
def GET(self):
web.header('Content-Type', 'text/html;charset=UTF-8');
web.header('Server','Python3/Server');
web.header('Coodie','NMSL')
return open(r'index.html','r').read()
return "<h1>你好!</h1>"
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()

This time we returned index.html write your html page in it. After server.py run to open the python services.

Tips: Replace only after the port with the port number to the program such as: server.py 23333

Published 16 original articles · won praise 9 · views 6567

Guess you like

Origin blog.csdn.net/weixin_42608762/article/details/103442997