Fun to learn python programming (7. It’s so easy to implement a small website. Introduction to using web.py)

Let’s take an example of a small website first. Just stay curious. Because interest is the best teacher, it can stimulate people's inner power of action. Here is a small website implemented using the web.py lightweight framework. You can see that it is not difficult to implement a small website. What can python be used for? Well a website is one of its many features.

Introduction to web.py framework

As its name suggests, web.py is a web framework using Python as the development language, which is simple and powerful. Russia's number one search engine, Yandex, is developed based on this framework, which Guido van Rossum considers to be the best Python web framework. Lightweight and compact, the author is the famous computer hacker Aaron Swartz (Aaron Swartz), a young and famous computer genius, and the famous social networking site Reddit Founder.

Government location:https://webpy.org/

github地址:GitHub - webpy/webpy: web.py is a web framework for python that is as simple as it is powerful. 

web.py follows simple design principles and is designed to help developers quickly build web applications.

Here are some of the features and benefits of the web.py framework:

1. Simple design: web.py's design philosophy is "do one thing and do it well". It provides a set of simple and intuitive tools and APIs to make development simple and clear.

2. Lightweight and fast: web.py is a lightweight framework without too many dependencies, so it is very fast and has low resource consumption.

3. URL mapping: web.py uses a simple URL mapping mechanism, making it very easy to handle different URL requests.

4. Built-in template engine: web.py has a built-in simple and powerful template engine, allowing developers to easily render data into templates.

5. Database support: web.py provides support for a variety of databases, including MySQL, PostgreSQL, SQLite, etc., allowing developers to easily interact with databases.

6. RESTful support: web.py provides good support for building RESTful APIs, allowing developers to easily create APIs that comply with RESTful design principles.

7. Open source code: web.py is an open source framework, its source code can be found on GitHub, and developers can freely use, modify and contribute the code.

All in all, web.py is a simple yet powerful Python web framework suitable for building small to medium-sized web applications. It focuses on simplicity, efficiency and flexibility, allowing developers to focus more on the implementation of business logic.

Use of web.py 

The simplest website

You need to download and install web.py before use. You can execute pip install web.py to install it. The default download is version 0.62, which supports python3.

pip install web.py==0.62

A most basic app.py contains the following contents: 

#-*- coding: utf-8 -*-
# 文件名:app.py
import web

# 表明访问的URL,这里表示的是所有响应,均由 class 对象 index 来响应
# 注:/(.*) 代表的是正则匹配url后面的所有路径,也就是响应任何请求
urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

# 表示 class 对象 index
# 传递参数:self,name(name指url路径/后面的内容)
class hello:
     # 响应GET请求(声明函数)
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'
    
# 当该.py文件被直接运行时,if __name__ == "__main__": 下的代码将被运行
# 当该.py文件作为模块被引入时,if __name__ == "__main__": 下的代码不会被运行
if __name__ == "__main__":
    app.run()

Start the application. Its default service address is http://127.0.0.1:8080/ . Next, you can open the browser and try accessing this address in the address bar to see the output.

python3 app.py

Yes, this is a small web application, but it is very simple and has no actual output. It is far different from most web pages with gorgeous interfaces you see on the Internet, but it doesn’t matter. This is just the cornerstone. If you want a beautiful web interface, you only need to edit and improve the HTML page, and add js and css to achieve the effect. .

If you want to display a web page, you can change it slightly:

#-*- coding: utf-8 -*-
# 文件名:app.py
import web    # 引入web.py库

# 表明访问的URL,这里表示的是所有响应,均由 class 对象 index 来响应
# 注:/(.*) 代表的是正则匹配url后面的所有路径,也就是响应任何请求
urls = (
     '/(.*)', 'index'
)

# 声明一个名叫app的“应用”
app = web.application(urls, globals())

# 表示 class 对象 index
# 传递参数:self,name(name指url路径/后面的内容)
class index:
    # 响应GET请求(声明函数)
    def GET(self,name):
        # 使用只读,二进制方式打开文件,读取到变量 index_text 中
        index_text = open('index.html','rb').read()
        # 输出变量 index_text 内的内容,也就是 index.html 内的HTML代码
        return index_text

# 当该.py文件被直接运行时,if __name__ == "__main__": 下的代码将被运行
# 当该.py文件作为模块被引入时,if __name__ == "__main__": 下的代码不会被运行
if __name__ == "__main__":
    # 运行这个服务器
    app.run()

Run app.py: Then you can open the web page to see the effect:

At this point, this simple web server is completed. Its function is to read the content of index.html and output the html code in index.html to the browser during access. In order to facilitate testing, the html file of the previous test is attached, the content is as follows:

<!DOCTYPE html>
<html lang="utf-8">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
</head>
<body>
    <h1>Web.py 真不错啊</h1>
</body>
</html>

An issue to note is that in Python, the open() function uses the system's default encoding to open the file by default. The exact default encoding depends on the operating system and configuration. In most cases, the default encoding for Windows systems is cp1252 and for Unix/Linux systems is utf-8 . If you want to open the file in a specific encoding, you can specify the parameter in the open() function, for example: encoding

index_text = open(abspath+'/index.html','r',encoding='UTF-8').read()

Pay attention to the above encoding issues, otherwise it will report:

 It should also be noted that under Windows, the specified path needs to be an absolute path, which is the abspath+'/index.html above.

If you want to open it with utf-8, this is it:

open(file_name, 'r', encoding='UTF-8')

If you want to open it with gbk encoding, it is like this:

open(file_name, 'rb')

Access static resources

Access static resources and web template examples:

# encoding: utf-8
import web
import datetime
import os

urls = (
    '/', 'index',
    '/hello', 'hello',
    '/login', 'login',
    '/add', 'add',
    '/delete', 'delete',
    '/(js|css|images)/(.*)', 'static'
)

#获取当前文件路径
abspath = os.path.dirname(__file__) 
#引入模板文件
render = web.template.render(abspath+"/templates/")

app = web.application(urls, globals())

#静态文件访问
class static:
    def GET(self, media, file):
        try:
            print(media+'/'+file)
            f = open(abspath+"/"+media+'/'+file, 'rb')
            return f.read()
        except:
             return '' # you can send an 404 error here if you want
    
#自定义数据
class MyData:
    def __init__(self, id, title):
        self.id = id
        self.title = title
             
class index:
    def GET(self):
        data = MyData(1,"洋洋")
        print(datetime.datetime.now())
        return render.index(data)

class login:
    def GET(self):
        print(datetime.datetime.now())
        return render.login()
       
class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'
    
class add:
    def POST(self):
        i = web.input()
        print(i)
        # print(datetime.datetime.now())
        raise web.seeother('/') 
    
class delete:
    def GET(self):
        print(web.ctx)
        t = int(web.ctx['query'][4 : : ])
        print(t)
        print(type(t))
        raise web.seeother('/')     
    
    
if __name__ == "__main__":
    web.config.debug = True
    app.run()

 Web page template index.html

$def with (data)
<div bordor="1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<h2 align="center" color="red">我的网站</h2>
    <table border="1" align="center">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>操作</th>
    </tr>
    <tr>
    <td> id="$data.id" </td>
    <td> $data.title </td>
    <td> <a href="/delete?id=$data.id" class="btn btn-danger btn-xs">删除</a> </td>
    </tr>
</table>
</div>
<form method="post" action="add">
<p><input type="text" name="title" /> <input type="submit" value="增加" /></p>
</form>

Web template login interface login.html

$def with ()
<link rel="stylesheet" type="text/css" href="/css/login.css">
<form id="login" action="" method="POST">
<table align="left">
<tbody>
    <tr>
        <td><label for="username">帐号</label></td>
        <td><input type="text" id="username" name="username" /><span class="validate_tip"></span></td>
    </tr>
    <tr>
        <td><label for="password">密码</label></td>
        <td><input type="password" id="password" name="password" /><span class="validate_tip"></span></td>
    </tr>
    <tr>
        <td></td>
        <td><a href="/" id="find_password">返回首页</a></td>
    </tr>
    <tr><td><input type="submit" id="login_btn" value="登录" /></td></tr>
</tbody>
</table>
</form>

Maybe you feel that the web pages implemented above are too rough and not beautiful enough. But do you know what the world’s earliest Internet page looked like?

The birth of the first web page in history

How did the world's first Internet web page come about?​ 

The world's first Internet web page was born on December 25, 1990 (opened to the public in August of the following year). It has a history of about 28 years. It was created by Tim Berners-Lee, the father of the World Wide Web. -Lee) and Robert Kallio built it together at CERN (European Commission for Nuclear Research), successfully realizing HTTP proxy and server communication through the Intel network for the first time. The success of this communication marked the arrival of the Internet and was of epoch-making significance.

After so many years, the Internet is developing rapidly, and various web pages are beautifully designed. They are no longer simple words or documents, but have become platforms for life and work one after another, creating various intersections with people's lives. It can be said that it is everywhere.

In recent years, the mobile Internet has developed rapidly. Mobile phones have become a necessity in people's lives. Web pages have also changed accordingly, focusing more on interaction and experience. Before this, many people thought that the web page was the Internet, or the Internet was the web page. However, the popularity of mobile Internet has made people feel that the Internet is a tool with infinite possibilities.

Tim Berners-Lee was the first to use hypertext to share information and invented the first web browser, WorldWideWeb, in 1990. In March 1991, he introduced the invention to his friend who worked at CERN. Since then, the development of browsers has been linked to the development of the Internet. The first website created by Tim Berners-Lee (and the first website in the world) was http://info.cern.ch/, which went online on August 6, 1991. It explained what the World Wide Web was What, how to use a web browser and how to set up a web server etc. Tim Berners-Lee later listed other websites on this website, so it was also the world's first World Wide Web directory.

In December 1994, Netscape Navigator released version 1.0 of the browser. This version supports all HTML2 language elements and some HTML3 language features. However, in the history of browser development, the Mosaic browser had been born before the Netscape browser. In fact, Mosaic was not the first web browser with a graphical interface, but Mosaic was the first to be widely used. Accepted browser, it introduced many people to the Internet.

For more introduction to the Internet, see this link:The first web page in history looked like this - Zhihu

You can visit the earliest webpage at http://info.cern.ch/. The earliest webpage looks like this:

Aaron Swartz Story

Let me tell you a story about Aaron Swartz, the author of web.py. Because it is quite inspirational and interesting, I will share it here. I hope you can benefit from it.

Schwartz was born in Chicago on November 18, 1986. His father is a software engineer and his mother is an artist. There was already the earliest Mac in the family when he was born. Schwarz had a strong learning ability since he was a child. In addition to his father's influence, Schwarz learned programming at a very young age.​ 

When I was 12 years old, I established a website called get.info (The info.org), which is a free online encyclopedia. Everyone can add and edit content on the website. At that time, when Schwartz was working on this website, Wikipedia had not yet appeared. At the age of 13, Swartz won an ArsDigita Award.

Because of this website, 14-year-old Schwartz was able to participate in the development of the RSS specification (a feed format specification used to aggregate websites that publish frequently updated data, such as blog posts, news, audio or video excerpts.) And became famous.

In 2004, Schwartz was admitted to Stanford University, but unfortunately, he dropped out the next year. After dropping out of school, he founded the famous Reddit social news website. The life story of Aaron Schwartz was made into the documentary "Son of the Internet" by director Nebenberg in 2014.

What Aaron said is quite touching——

I believe you should really ask yourself every moment, what is the most important thing in this world that I can participate in?

Tips for improving efficiency

If you're not doing the most important thing, then why?

He shared an article a long time ago called "Secrets to Improving Efficiency."

The writing is very good and I benefited a lot from reading it. I will share it here:

Someone must have said to you, "The time you spend watching TV could be used to write a book." It is undeniable that writing a book is definitely a better use of time than watching TV, but the establishment of this conclusion requires an assumption: "Time is interchangeable", which means that the time spent watching TV can easily be used to write a book. But unfortunately, this is not the case.

Different times have different quality levels. If I realize on my way to the subway that I've forgotten my notebook, it's hard to concentrate on writing. Likewise, it's hard to concentrate when you're constantly interrupted. There are also some psychological and emotional factors here. Some days I am in a good mood and willing to take the initiative to do something, but other days I feel so depressed and tired that all I can do is watch TV.

If you want to become more efficient, you must be aware of this fact and deal with it well. First, you have to make good use of different kinds of time. Secondly, you have to make your time more efficient.

Use your time more efficiently

Choose the right thing

Life is so short, why waste your time doing meaningless things? It’s easy to do things that make you feel comfortable, but you should ask yourself why you are doing them? Is there something more important waiting for you to do? Why don't you do those things? These questions are difficult to answer, but solving each one will make you more productive.

This doesn't mean that all your time should be spent doing the things that matter most. That’s certainly not the case with my time (otherwise, I wouldn’t be writing this article right now). However, it is an important measure of how fulfilling my life is.

Collect a lot of things

Another secret that many people know is that you will be most efficient if you identify a problem and devote all your energy to solving it. I found this to be very difficult to achieve. Right now, for example, I am working out, drinking orange juice, clearing my desk, chatting with my brother, and writing this article. Throughout the day today, I wrote this article, read a book, ate something, responded to a few emails, chatted with some friends, bought something, and revised several other articles. I backed up my hard drive and sorted out my book list.

There are a lot of different projects that allow me to do different things with different qualities of time. What's more, there are other things to do when you get stuck or bored.

This will also make you more creative. Creativity is when you apply what you have learned elsewhere to your work. If you work in many different directions at the same time, you will get more ideas and creativity.

make a list

It’s not difficult to find something different to do at the same time; most people have lots and lots of things to do. But if you try to keep them all in your head, they will slowly disappear. Remember that the mental stress of all these things can overwhelm you. The solution is still simple: write them down.

Once you have a list of things to do, you can better organize them into categories. For example, my list includes: programming, thinking, errands, reading, entertainment and rest.

Most projects include many different tasks. Take writing this article as an example. In addition to the actual writing process, it also includes reading other articles about procrastination, considering each part of the article, organizing sentences, asking others for questions, etc. Each task belongs to a different part of the list, so you can do it at the right time.

Integrate to-do lists into your life

Once you have such a to-do list, all you need to do is remember it from time to time, and the best way to remember it is to put it where you can see it. For example, I always keep a stack of books on my desk, and the one on top is the one I'm currently reading. When I want to read, I just grab a book from above and read it.

I do the same for watching TV/movies. When I'm interested in a movie, I put it in a special folder on my computer. Whenever I want to take a break and watch a movie, I open that folder.

I have also thought about some more in-depth ways. For example, I mark some articles I want to read as "to be read", and when I want to surf the Internet, I will look at the unread articles accumulated in the past.

Improve the quality of your time

Maximizing the use of time as above is not enough, it is more important to improve the quality of your own time. So what exactly do you do?

avoid being disturbed

For tasks that require concentration, you should try to avoid interruptions. A very simple way is to go to a place where no one can disturb you. Another way is to tell the people around you not to disturb you for a while. Don't go too far on this point. You should be interrupted when you're wasting time. Helping others solve their problems is certainly a better use of time than sitting around watching the news.

Alleviate psychological constraints

Eat, sleep, and exercise: When you feel hungry, tired, or anxious, the quality of your time will be low. The solution to this problem is simple: eat, sleep, and exercise. Saying to yourself, "I'm tired, but I can't rest because I have to work" will make you feel like you're working hard, but in fact you'll be more productive after resting. Since you have to go to bed sooner or later, you might as well get some rest first to improve your efficiency during the remaining time.

hang out with happy people

Being around happy people will make you happy and make you more relaxed. Maybe many people are willing to hide in their houses, not have contact with other people, and work hard. They think that this way their time will not be "wasted", but in fact this will make them depressed and their work efficiency will be greatly reduced.​ 

Procrastination

What is mentioned above is not the focus of the problem. The biggest problem regarding efficiency is "procrastination". Although many people won’t admit it, almost everyone procrastinates to some extent. So how to avoid it?

What is procrastination? From the outside looking in, you're doing fun things (like playing games, watching the news) instead of doing real work. But the crux of the question is: why on earth do you do this? What exactly is going on in your head?

I've spent a lot of time researching this, and the best explanation I can give is that the brain assigns a "brain force field" to each task. Have you ever played with two magnets interacting? If you put them with opposite poles, they will repel each other and you will feel the magnetic force between them. The more you try to put them together, the more repulsive you will feel.

The same goes for the mind and spirit. It is invisible and intangible, but you can feel its presence. And the closer you try to get to it, the further away it will get from you.

You can't overcome the repulsion between two fields by brute force. Instead, what you should do is reverse direction.

So what creates the "spiritual force field"? There seem to be two main reasons: whether the task is difficult and whether the task is assigned.

Difficult task

Break down tasks

One reason a task is difficult is that the task is ambitious. For example, if you want to make a recipe construction program, no one can complete it in one go. This is a goal rather than a task. A task is a concrete concept that moves you closer toward your goal. A good task is one that you can implement immediately, such as "Draw a sketch showing the recipe."

When you complete the previous task, the next step will become clearer. You'll consider what constitutes a recipe, what kind of search mechanism you need, how to build a database of recipes, and so on. This way you build an engine where each task leads to the next.

For every larger project, I think about a series of tasks I need to complete and add those tasks to my to-do list. Similarly, when I finish some tasks, I will add the tasks that need to be completed next to the task list.

Simplify tasks

Another reason that makes the task difficult is that it is too complex. The task of "writing a book" may seem overwhelming to you, so start by writing an article. If even one article feels too much, then write a paragraph summary first. The most important thing is to actually do some work and make real progress.

Once you clarify your task, you can judge it more clearly and understand it more easily. It's easier to improve something that already exists than to create something from scratch. If you write a paragraph, then little by little, it will become an article and eventually a book.

consider it seriously

Often solving a difficult problem requires some inspiration. If you are not familiar with that field, you should start by studying the field, learn from other people's experiences, slowly study and understand the field, and make some small attempts to see if you can master this field.

assigned tasks

Assigned tasks are those that you are asked to complete. Many psychological experiments have shown that when you "stimulate" other people to do something, they are less likely to do that thing well. External stimuli such as rewards and punishments kill “intrinsic motivation”—your genuine interest in a problem. The human brain has an innate resistance to what it is asked to do.
This phenomenon is not limited to what other people ask you to do, but also occurs when you assign tasks to yourself. If you say to yourself, "I should do X well, it's the most important thing for me right now," then you will feel that X suddenly becomes the most difficult thing in the world. However, once Y becomes the "most important thing", the original X becomes simple again.

Make up a task

If you want to accomplish X, tell yourself to do Y. Unfortunately, it's hard to fool yourself like this because you know exactly what you're doing.

Don’t assign tasks to yourself

It seems tempting to give yourself tasks, such as saying to yourself "I have to finish writing this article before going to eat," but it is even worse to let others pretend to give you some tasks. But both methods will make you less efficient. In fact, you are still assigning tasks to yourself, and your brain will just avoid it.

make things interesting

Difficult work may not sound pleasurable, but in fact it’s probably what makes me happiest. Not only does a difficult problem allow you to focus your full attention, but it also makes you feel great and accomplished when you complete it.

So the secret to helping yourself get something done is not to convince yourself that you have to do it, but to convince yourself that it is really interesting. If something isn't interesting, all you have to do is make it interesting.

Summarize

The real secret to efficiency is to "listen to yourself", eat when you are hungry, sleep when you are tired, take a break when you are bored, and do interesting and fun projects.

This seems easy, but some ideas in society are leading us in the opposite direction. To become more effective, all we need to do is turn around and “listen to ourselves.”

Other resources

https://webpy.org/

Super detailed tutorial: How to develop your website with Python (1) - Zhihu

python - UnicodeDecodeError:'gbk' codec can't decode byte 0x80 in position 0 illegal multibyte sequence - Stack Overflow

Internet web page (How was the world's first Internet web page born?)-Tech Times

The first web page in history looked like this - Zhihu

Take a look at the web pages from twenty years ago and trace the memories of the Internet - Life Stories - Memories Network 

Looking back at history: The Internet was born at 22:30 on October 29, 1969

おすすめ

転載: blog.csdn.net/qq8864/article/details/134523232