web开发就是基于浏览器进行人机交互,当访客登录到指定网址后,不仅可以看到浏览器渲染的画面,同时还可以与后台进行一些操作,再通过浏览器返回后台服务器处理的结果,这段时间一直在摸索利用flask框架来做点有意思的事,这不,他就来了。相对于django框架,flask具有以下特点,

Flask:

小巧、灵活,让程序员自己决定定制哪些功能,非常适用于小型网站。
对于普通的工人来说将毛坯房装修为城市综合体还是很麻烦的,使用Flask来开发大型网站也一样,开发的难度较大,代码架构需要自己设计,开发成本取决于开发者的能力和经验。
Django:

大而全,功能极其强大,是Python web框架的先驱,用户多,第三方库极其丰富。

非常适合企业级网站的开发,但是对于小型的微服务来说,总有“杀鸡焉有宰牛刀”的感觉,体量较大,非常臃肿,定制化程度没有Flask高,也没有Flask那么灵活。

下面就是具体开发过程,技术栈包括简单的html+css+mysql+flask

(1)前端界面

     显示的结果如下

具体代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test's forum</title>
    <style>
        h1,form {text-align: center;}
        textarea {width:800px;height:200px;}
        div.post {
            border: 5px solid #888;
            padding: 20px 20px;
            margin: 20px 20%%; }
        hr.postbound {width:50%%;}
        em.date {color: #888;}
    </style>
</head>
<body>
    <h1>test's forum</h1>
    <form action="" method=post>
        <div>
            <textarea name="content" id="content" cols="30" rows="10"></textarea>
        </div> 
        <div>
            <button id="go" name="bt1" type="submit">Enter there to post in test's forum</button>
            <button id="del" name="bt2" type="submit">delete a slice of data from forum</button>
        </div>
    </form>
    
    <!-- post内容会在这里 -->
    %s
</body>
</html>

(2)数据库db

        这里采用的是mysql数据库,可以根据自己的要求进行替换,不过需要你自己先建表,比如posts表

create database forum; ##创建数据库
 
use forum; ###使用该数据库

create table posts (content varchar(100) not null,time datetime not null,id int(10) auto_increment );  ###创建posts表

然后聊天内容的增删操作

import pymysql

DBHost='localhost'
DBUser="root"
DBPassword="xxxxx"
DBName="forum"


def get_post():
    try:
        db=pymysql.connect(DBHost,DBUser,DBPassword,DBName)
        print('get数据库连接成功')
    except pymysql.Error as e:
        print("get数据库连接失败"+str(e))
    c=db.cursor()
    c.execute("select content,time from posts order by time desc")
    posts=c.fetchall()
    db.close()
    return posts

def add_post(content):
    try:
        db=pymysql.connect(DBHost,DBUser,DBPassword,DBName)
        print('post数据库连接成功')
    except pymysql.Error as e:
        print("post数据库连接失败"+str(e))
    c=db.cursor()
    sqlquery="insert into posts(content,time) value (%s,%s)"
    c.execute(sqlquery,content)
    db.commit()
    db.close()

def del_cnt():
    try:
        db=pymysql.connect(DBHost,DBUser,DBPassword,DBName)
        print('post数据库连接成功')
    except pymysql.Error as e:
        print("post数据库连接失败"+str(e))
    c=db.cursor()
    sqlquery="delete from posts where id like (select * from (select max(id) from posts) tmp)"
    c.execute(sqlquery)
    db.commit()
    db.close()

(3)flask框架

    基于前后端的一些操作,整合如下

from flask import Flask,request,redirect,url_for
from tiebadb import add_post,get_post,del_cnt
import time
import tkinter.messagebox as tm

app=Flask(__name__)

HTML_WRAP='''\
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test's forum</title>
    <style>
        h1,form {text-align: center;}
        textarea {width:800px;height:200px;}
        div.post {
            border: 5px solid #888;
            padding: 20px 20px;
            margin: 20px 20%%; }
        hr.postbound {width:50%%;}
        em.date {color: #888;}
    </style>
</head>
<body>
    <h1>test's forum</h1>
    <form action="" method=post>
        <div>
            <textarea name="content" id="content" cols="30" rows="10"></textarea>
        </div> 
        <div>
            <button id="go" name="bt1" type="submit">Enter there to post in test's forum</button>
            <button id="del" name="bt2" type="submit">delete a slice of data from forum</button>
        </div>
    </form>
    
    <!-- post内容会在这里 -->
    %s
</body>
</html>
'''

POST='''\
<div class=post><em class=date>%s</em><br>%s</div>
'''

@app.route('/',methods=['GET','POST'])
def main():
    posts="".join(POST % (date,text) for text,date in get_post())
    html=HTML_WRAP % posts
    return html

@app.route('/',methods=['POST','GET'])
def post():
    try:
        bt=request.form["bt2"]
        message=request.form['content']
        if bt is "" and message is "":
            del_cnt()
    except Exception as e:
        print("错误类型:{}".format(e))
        message=request.form['content']
        t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        data = (str(message), str(t))
        add_post(data)

    return redirect(url_for('main'))

if __name__=='__main__':
    app.run(host="0.0.0.0",port=8000,debug=True)

这样,当整个代码run起来后,如果显示如下结果则表示没错,打开浏览器输入localhost:8000即可

最后补充一句,这只是一个简单的及时聊天系统,如果你想和朋友在一个局域网内实现自己的简单沟通,记得提前打开你的8000端口,或者关闭防火墙,然后让你得朋友在浏览器中输入你电脑的ip:8000即可打开聊天对话框。好了,今天就先到这里,下次有机会再一起分享。

 

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐