学习使用python网络框架flask做网站

Words
1696
Reading
8 min
4y
Listen to this post
~11 min

接触数字货币也有好几年了,也有一个愿望,就是有一天也能自己开发小项目。虽然不是专业的,编程只是一个业余小爱好。不过数字货币的去中心化特点,和许多大佬打造了很多工具,还是让实现这个愿望单门槛下降了不少。当然第一步要学会做网站。这段时间一直在看python的web框架flask的视频教程,感觉flask还是很好用的,用python做网站没有想象的那么难。这里稍微整理一下学习的内容:

目录

  • HTML的基本用法
    • 网页基本结构

    • 常用标签

    • 表单,收集数据

  • Flask的基本用法
    • 路由与函数

    • 模板

    • session的操作

  • 数据库sqlite的基本用法
    • 常用命令

    • 在python中使用sqlite

    附录: 我的练习程序



    用flask做网站,基本逻辑还是很简单的,用flask库编写的python脚本运行在服务器端,通过网页表单收集数据,在后台处理数据,然后渲染网页模板,在需要的地方显示处理后的内容。所以用flask做网站的工作主要由两部分,一部分,就是用HTML语言编写网页模板,第二部分就是用python调用flask库的组件,编写后台操作。先来看看如何使用HTML语言编写简单的网页模板:

    一、HTML的基本用法

    1.网页基本组成部分:

    html页面的组成部分:1、DOCTYPE声明部分,可以告知Web浏览器页面使用了哪种HTML版本;2、head头部,主要包含编码声明、标题、样式表嵌入等;3、body内容部分,包含文档的所有内容;3、footer底部,定义文档或节的页脚。

    其中body就是网页内容区域,我们下面说到的标签都是添加到这个区域。

    2.常用标签

    html标签分两类,一类叫双标签,形如<**>内容</**>,一类叫单标签,形如<>。在标签里面还可以添加属性,进一步定义标签内容,多个属性之间要用空格隔开。
    常用的标签有:

    标签名 用途
    h1,h2,h3,h4,h5 标题标签
    table 表格标签
    tr,th,td 分别是表格行(row),表头(head),数据(data)标签。
    a 锚标签,一般用来表示网页链接。
    img 图片标签,插入图片。
    br 换行。
    form 表单标签,用于收集用户数据,详见下一节。

    3.表单,收集数据

    表单是用网页收集数据用的,可以设置多种控件。表单标签form提示标签范围里的内容是表单,input标签可以通过各种属性实现各种控件。一个简单的登陆对话框表单如下:

      <h1>用户登陆<h1>
      <form method='POST' >
        <input type='text' name='user'/>
        <br>
        <input type='text' name='password'/>
        <input type='submit' value='提交'/>
      </form>
    

    image.png

    二、Flask的基本用法

    Flask是python的一个web框架,我的理解就是封装很多和制作网站相关的工具,就像一个工具箱,可以很容易的制作出网站。这里我参照教程做了一个简单的网站,紧跟时事,这个网站的功能就是收集西方国家给乌克兰提供的武器类型和数量,存入数据库中,可以在网页上将数据显示出来,也可以通过网页界面,添加和删除条目。当然只有登录的用户才有权进行这些操作。
    开始编程前,还是先用venv命令建立一个虚拟环境,再通过pip安装flask库和需要的依赖,就可以在虚拟环境下进行开发了。

    1.路由与函数

    flask的使用还是很简单,先用装饰器指定一个路由,下面紧跟的函数就是当浏览器访问这个地址时调用的程序,比如:

    @app.route('/login')
    def login():
       pass
    

    这段代码的意思就是当浏览器访问http://xxx.xxx/login时,服务器就会执行login()这个函数。

    根据需求,我们开发的这个网站需要一个登录路由"/login",数据展示路由"/index",添加和删除条目的路由"/add"和"/delete"。

    2.模板

    模板就是显示的网页,用html语言写成,flask可以用程序中的变量更换指定的内容,需要程序提供的内容用两层花括号括起来,比如{{country}},在python脚本中用render_template('xxx.html',country='美国'这条代码就可以把对应的内容显示成“美国”。
    同时模板还支持选择,和循环代码,不过是用{%将代码括起来。比如:

    {% for user in users %}
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
    {% endfor %}

    3.session

    session的功能是在用户浏览器中存储信息,这里使用它主要是用来实现登录验证功能,只有成功登录的用户,才能在浏览器中存储用户信息。只有浏览器中有用户信息的用户才能浏览数据库内容,添加、删除条目。要使用seesion,首先要设置一个密钥用于加密信息app.secret_key='9425jfdswol'然后就可以字典的形式在session中存储信息,比如session['name']='xxxx',或者删除信息session.pop('name')

    三、数据库sqlite的基本用法

    网站要存储数据,就要用到数据库,python自带有sqlite数据库,非常方便。

    1.常用命令

    1.建表:
    sqlite> create table usr(id integer primary key, name text,age integer null, gender text, salary real not null);
    2.删除表
    sqlite> drop table usr;
    3.增:
    sqlite> insert into usr(id, name, age, salary) values(2, 'liu', 20, 6000);
    4.删
    sqlite> delete from usr where id = 2;
    5.改:
    sqlite> update usr set gender = 'man' where id = 3;
    6.查:
    sqlite> select * from usr where id = 2;
    7.在表中添加字段
    sqlite>alter table usr add column country text;

    2.在python中使用sqlite

    在python中可以直接使用sqlite,先倒入模块sqlite3。然后在连接到数据库文件,创建一个指针,你可以把指针想象成一个代理人,对它下命令,它就会完成任务。如果通过指针修改了数据库,要用commit()提交修改才会生效。示例代码如下:

    import sqlite3
    
    conn = sqlite3.connect('test.db')
    c = conn.cursor()
    print ("数据库打开成功")
    
    c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
          VALUES (1, 'Paul', 32, 'California', 20000.00 )")
    
    c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
          VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
    
    c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
          VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )")
    
    c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
          VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )")
    
    conn.commit()
    print ("数据插入成功")
    conn.close()
    

    附录: 我的练习程序

    image.png

    1.主程序:用户管理.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from flask import Flask,render_template,request,redirect,session
    import sqlite3
    
    def read_database():
        connection = sqlite3.connect('testdb.db')
        cursor = connection.cursor()
        cursor.execute('select * from support_weapon')
        data = cursor.fetchall()
        connection.close()
        support_weapon={}
        for i in data:
            support_weapon[i[1]]=[i[2],i[3]]
        return support_weapon
    
    def add_to_database(country,weapon_type,quantity):
        connection = sqlite3.connect('testdb.db')
        cursor = connection.cursor()
        cursor.execute('select count(*) from support_weapon')
        n = cursor.fetchall()[0][0]
        print(n)
        cursor.execute('insert into support_weapon values (?,?,?,?)',(n,country,weapon_type,quantity))
        connection.commit()
        connection.close()
    
    def delete_from_database(country):
        connection = sqlite3.connect('testdb.db')
        cursor = connection.cursor()
        country="'"+country+"'"
        cursor.execute('delete from support_weapon where country=%s'%country)
        connection.commit()
        connection.close()
    
     
    
    app= Flask(__name__)
    app.secret_key='djsf32fdsfjf'
    
    @app.route('/login',methods=['POST','GET'])
    def login():
        if request.method=='GET':
            return render_template('login.html') 
        user=request.form.get('user')
        pwd=request.form.get('password')
        print(user,pwd)
        session['user']=user
        if user == 'cheva' and pwd == '123456':
            return redirect('/index')
        return render_template('login.html',errorinfo='账号密码不匹配')
    
    @app.route('/index')
    def index():
        if not session.get('user'):
            return redirect('/login')
        support_weapon=read_database()
        return render_template('index.html',data=support_weapon) 
    
    @app.route('/del/')
    def del_data(country):
        delete_from_database(country)
        support_weapon=read_database()
        return render_template('index.html',data=support_weapon) 
    
    @app.route('/add',methods=['POST','GET'])
    def add_data():
        if request.method=='GET':
            return render_template('login.html') 
        data=request.form
        add_to_database(data['country'],data['weapon_type'],data['number'])
        support_weapon=read_database()
        return render_template('index.html',data=support_weapon) 
    
    @app.route('/logoff')
    def logoff():
        session.pop('user')
        return redirect('/login')
    
    
    if __name__=='__main__':
        app.run(debug=True)
    
    

    2.网页模板

    网页模板要放在template文件夹下面,程序会直接调用:
    login.html:

    <!DOCTYPE html>
    <html>
    <head>
      <title>登录</title>
    </head>
    <body>
      <h1>用户登陆<h1>
      <form method='POST' >
        <input type='text' name='user'/>
        <br>
        <input type='text' name='password'/>
        <input type='submit' value='提交'/>{{errorinfo}}
      </form>
      <textarea rows=10 cols=30>
        这是多行文本
      </textarea>
      <table border="1" width=500 height=50 cellspacing=0>
        <tr>
          <th>1</th>
          <th>1</th>
          <th>1</th>
        </tr>
        <tr>
          <td>1</td>
          <td>1</td>
          <td>1</td>
        </tr>
    
      </table>
     </body>
    </html>
    

    index.html:

    
    <!DOCTYPE html>
    <html>
    <head>
    <title>Input Page</title>
    </head>
    <body>
    <form method='POST' action="save">
    <input type="text" name="username" id="uname"/>
    <input type="submit" value="Submit"/>
    </form>
      <table border="1" width=500 height=100 cellspacing=0>
        <tr>
          <th>国家</th>
          <th>火炮型号</th>
          <th>数量</th>
          <th>操作</th>
        {% for key in data %}
        <tr align="center">
          <td>{{key}}</td>
          <td>{{data[key][0]}}</td>
          <td>{{data[key][1]}}</td>
          <td><a href='/del/{{key}}'>删除</a></td>
        </tr>
        {%endfor%}
      </table>
    <form method='POST' action='/add'>
      <input type=text name='country'>
      <input type=text name='weapon_type'>
      <input type=text name='number'>
      <input type=submit value='新增'>
    </form><br>
    <a href="/logoff">退出登录</a>
    </body>
    </html>
    
    学习使用python网络框架flask做网站 | Ecency