Table of Contents
Conditions
Development language:
Library:
Editor:
The simplest web server
Processing URLs
Use templates
Use template engine
Finished product
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

Sep 13, 2018 pm 05:35 PM
python web development

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles