Home > Web Front-end > JS Tutorial > Teach you how to build a simple website: Python development web server

Teach you how to build a simple website: Python development web server

坏嘻嘻
Release: 2018-09-13 17:35:31
Original
4770 people have browsed it

There are countless web frameworks in Python, from basic tiny architectures to complete architectures, and they have their own advantages. So you're ready to use it to do some web development, but before getting into the details, let's start from the beginning.

Goal

Build a picture viewing website using existing rich picture resources

Conditions

Development language:

python3

Library:

flask: an open source python web server framework
jinja2:flask’s default template engine

Editor:

Recommended pycharm

The simplest web server

python provides us with an interface: WSGI: Web Server Gateway Interface
It only requires web developers to implement a function to respond to HTTP ask. Without touching TCP connections, HTTP raw request and response formats.
The following example is the simplest web application:

# hello.pydef application(environ, start_response):
    start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/html&#39;)])    return [b&#39;<h1>Hello, Python web!</h1>&#39;]# server.py# 从wsgiref模块导入:from wsgiref.simple_server import make_server# 导入我们自己编写的application函数:from hello import application# 创建一个服务器,IP地址为空,端口是8000,处理函数是application:httpd = make_server(&#39;&#39;, 8000, application)
print(&#39;Serving HTTP on port 8000...&#39;)# 开始监听HTTP请求:httpd.serve_forever()
Copy after login
  • environ: a dict object containing all HTTP request information;

  • start_response : A function that sends an HTTP response.

Put the two scripts in the same directory, run server.py, and visit http://127.0.0.1:8000 to see the effect.

Processing URLs

In fact, web applications are the processing of different URLs.
We will modify hello.py

def application(environ, start_response):
    method = environ[&#39;REQUEST_METHOD&#39;]
    path = environ[&#39;PATH_INFO&#39;]    if method==&#39;GET&#39; and path==&#39;/&#39;:        return handle_home(environ, start_response)    if method==&#39;POST&#39; and path=&#39;/signin&#39;:        return handle_signin(environ, start_response)
...
Copy after login

This will handle two urls, '/' and '/signin'
Of course you can keep writing like this...if you are not tired .

Use templates

Since the above method is too tiring and slow, let’s learn something advanced:
flask

Look at the code

from flask import Flaskfrom flask import request

app = Flask(__name__)@app.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])def home():
    return &#39;<h1>Home</h1>&#39;@app.route(&#39;/signin&#39;, methods=[&#39;GET&#39;])def signin_form():
    return &#39;&#39;&#39;<form action="/signin" method="post">
              <p><input name="username"></p>
              <p><input name="password" type="password"></p>
              <p><button type="submit">Sign In</button></p>
              </form>&#39;&#39;&#39;@app.route(&#39;/signin&#39;, methods=[&#39;POST&#39;])def signin():
    # 需要从request对象读取表单内容:
    if request.form[&#39;username&#39;]==&#39;admin&#39; and request.form[&#39;password&#39;]==&#39;password&#39;:        return &#39;<h3>Hello, admin!</h3>&#39;
    return &#39;<h3>Bad username or password.</h3>&#39;if __name__ == &#39;__main__&#39;:
    app.run()
Copy after login

Attention , this is a single file.
Let’s analyze this script:
Flask automatically associates URLs with functions internally through Python’s decorators.
After starting the operation, we visit
'/', and the page we see is a "HOME" word
'/signin'. At this time, we access it through GET, and we see a form, fill in 'admin' ' and 'password', click login——>
'/signin', now accessed through POST, but what you see is Hello, admin! or Bad username or password.

For those who don’t know GET For students with POST and HTML forms, it is recommended to learn the basics of HTML.

But this is still a bit inflexible. All the content that users see when accessing needs to be written out and cannot be reused. It is too troublesome.

Use template engine

The template solves the above problem. The problem. Let’s look at a piece of code first

from flask import Flask, request, render_templateimport os

app = Flask(__name__)@app.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])def home():
    path = &#39;/&#39;
    all_file = os.listdir(path)    return render_template(&#39;home.html&#39;,all_file = all_file)if __name__ == &#39;__main__&#39;:
    app.run()
Copy after login

Here we read the names of all the files in the root directory and pass them to the html template page

Then, create the directory templates in the same directory as .py, here What is stored is our template. The special thing about the template is that you can use python instructions and variables to write the instructions

{{ in html

home.html

{% for i in all_file %}    <a href="/page/{{ i }}">{{ i }}</a>{% endfor %}
Copy after login

{% %} What is written in }} is the variable

, so the final result is that multiple tags will be generated, and the name of the tag is the directory name.

The above basic tutorial refers to Liao Xuefeng.

Then, the foundation has been completed, and the next step will be the finished product:

Finished product

Use the pictures we crawled last time to build the website, good idea!
Here, create a static directory in the same directory as the .py script to store images. (The picture will not be linked if it is placed in the outer layer of the directory where .py is located)

#beautiful_pic.pyfrom flask import Flaskfrom flask import requestfrom flask import render_templateimport os

app = Flask(__name__)#显示所有文件夹@app.route(&#39;/&#39;,methods=[&#39;GET&#39;,&#39;POST&#39;])def list_all():
    path = &#39;./static/mzitu/&#39;
    all_pic = os.listdir(path)    return render_template(&#39;welcome.html&#39;,all_pic = all_pic)#具体展示图片@app.route(&#39;/<path>&#39;,methods=[&#39;GET&#39;,&#39;POST&#39;])def list_pic(path):
    #错误链接无法找到图片目录就提示错误链接
    if(path not in os.listdir(&#39;./static/mzitu/&#39;)):        return render_template(&#39;error.html&#39;)
    pic_path = &#39;./static/mzitu/&#39; + path
    all_pic = os.listdir(pic_path)    return render_template(&#39;pic.html&#39;,title = path,all_pic = all_pic)if __name__ == &#39;__main__&#39;:    #port为端口,host值为0.0.0.0即不单单只能在127.0.0.1访问,外网也能访问
    app.run(host=&#39;0.0.0.0&#39;,port=&#39;2333&#39;)
Copy after login

Then the template file
welcome.html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>欢迎来到福利页面</title></head><body>
    {% for i in all_pic: %}        <a href="/{{i}}">{{i}}</a>
        <br><br>
    {% endfor %}</body></html>
Copy after login

pic.html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>{{ title }}</title></head><body>
    {% for i in all_pic %}    <img src="./static/mzitu/{{title}}/{{i}}" alt="{{i}}">
    <br>
    {% endfor %}</body></html>
Copy after login

error .html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>出错了</title></head><body>
    你要访问的页面不存在...    <br>
    <a href="/">点此返回首页</a></body></html>
Copy after login

Related recommendations:

Eclipse PyDev Django Mysql to build a Python web development environment_MySQL

First time entering the Web For development, which one should I learn, php, python or ruby?

The above is the detailed content of Teach you how to build a simple website: Python development web server. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template