【flask-搭建Web】

这个小项目的代码是基于https://github.com/anfederico和https://github.com/xuweicn1两位的工作,让我可以几天内从知道flask的概念到把网页部署到阿里云。感谢造轮子的大神。
整个小项目的代码可以到https://github.com/zhangjipinggom/flask-sql下载

一、成品效果
首先登陆界面,注册或登陆成功后将进入操作界面。可以编辑各项内容、计算得分、下载生成的文件。具体的内容需要看代码

二、中途采坑及重点总结
1. 前端(html)和后端(.py)实现数据传输的方式:
以下面的代码为例。student_single这个函数可以被网页通过url_for()调用,调用时候往这个函数传入参数。最后的render_template()参数中,第一个为要渲染的网页,后面的参数可以向这个网页传递这些参数。这网页中通过{{变量名}}这样的方式来引用。

@app.route('/student_single/<name_student>')
def student_single(name_student):
    student_test = Student.query.filter_by(name=name_student).first()
    todos_student = Todo.query.filter_by(student=student_test).all()
    scores = {}
    categories = Category.query.all()
    score_all = 0
    for category in categories:
        score = 0
        todos = Todo.query.filter_by(student=student_test, category=category)
        for todo in todos:
            score += todo.scoreweight.value
            score_all += todo.scoreweight.value
        scores[category.name] = score
    scores["All"] = score_all
    return render_template(
        'student-single.html',
        todos=todos_student,
        categories=Category.query.all(),
        student=student_test,
        scoreweights=ScoreWeight.query.all(),
        scores=scores
    )

可以参考https://blog.csdn.net/weixin_41279532/article/details/84497881

2.  生成excel文件并下载:
如果在这个过程中提示Latin.....utf-8编码错误。注意下面函数的参数:
response.headers["Content-Disposition"] = \ "attachment;" \ "filename*=UTF-8''{utf_filename}".format( utf_filename=quote(basename.encode('utf-8')) )

@app.route('/student_single/<name_student>/')
def student_download(name_student):
    student_test = Student.query.filter_by(name=name_student).first()
    dict_w = {}
    categories = Category.query.all()
    score_all = 0
    length_max = 0
    dict_w["姓名"] = [name_student]
    for category in categories:
        score = 0
        content = []
        todos = Todo.query.filter_by(student=student_test, category=category)
        for todo in todos:
            content += [todo.description]
            score += todo.scoreweight.value
            score_all += todo.scoreweight.value
        dict_w[category.name] = content
        dict_w["score_"+category.name] = [score]
        length_max = max(length_max, len(content))
    dict_w["ScoreAll"] = [score_all]

    for key0 in dict_w.keys():
        length0 = len(dict_w[key0])
        if length0 < length_max:
            dict_w[key0] += [""] * (length_max - length0)

    df = pd.DataFrame(dict_w)
    out = io.BytesIO()
    writer = pd.ExcelWriter(out, engine="xlsxwriter")
    df.to_excel(excel_writer=writer, index=False, sheet_name="{}".format(name_student))
    writer.save()
    writer.close()
    response = make_response(out.getvalue())
    basename = "{}.xlsx".format(name_student)
    response.headers["Content-Disposition"] = \
        "attachment;" \
        "filename*=UTF-8''{utf_filename}".format(
            utf_filename=quote(basename.encode('utf-8'))
        )
    return response

这里可以参考https://blog.csdn.net/qq_35318838/article/details/101354968
https://www.cnblogs.com/gresstant/p/7943056.html

3.  将代码部署到云端,让手机或者其他代码也能访问自己的网
(1)方式一:用python anywhere https://www.pythonanywhere.com/
         这种方式最简便。但是我部署的时候运行出来的结果和我自己在本地跑的不一致,现在也没找到原因。不得不用第二种方法。
(2)服务器+nginx
网上教程太多,也折腾了好几个。最后是下面这个博客最简单的第三种方法实现的
https://www.jianshu.com/p/61d18009b657


总结起来也就几步:
a. 安装nginx(sudo apt-get install nginx)
b. 配置Nignx--(cd //etc/nginx/nginx.conf)

 #只用nginx代理的配置
    server {
         listen          80;
         server_name     47.106.218.225;  # 阿里云公网ip
 
         location / {
            proxy_pass    http://127.0.0.1:5000;      # 本机:启动端口(此处端口与项目端口一致)      
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
     }

c. 重启nginx:

nginx -s reload
如果出现报错:nginx: [error] open() "/var/run/nginx.pid" failed (2: No such file or directory)
可能是nginx服务没有启动
systemctl start nginx  # 启动nginx

 

d. 在服务器上运行主程序。比如 python app.py
然后在其他电脑或手机输入ip(比如http://47.106.218.225) 就可以访问呈现运行的结果

 

4.  db.create_all()加的地方要注意

发布了67 篇原创文章 · 获赞 19 · 访问量 8万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章