利用Flask开发一个Web程序

打印 上一主题 下一主题

主题 912|帖子 912|积分 2736

开发情况 : Linux系统,语言: Python,Html, Css
利用Flask实现一个WatchList的Web程序,部分代码和图片都是来自:Flask 入门教程,我在此基础上修改了一下,末了的效果如下:

1. 安装 Flask和一些基本插件

  1. pip install flask
  2. pip install Flask-SQLAlchemy
  3. pip install pymysql
复制代码
假如安装比力慢的话,可以加上 -i https://pypi.tsinghua.edu.cn/simple
2. 创建项目布局

创建一个文件夹来存放你的项目文件。项目的基本布局如下:
  1. WatchList/{static/images style.css} {template/index.html login.html} app.py
复制代码
3.在WatchList目录下创建虚拟情况并进入虚拟情况

  1. python3 -m venv env
  2. scoure ./env/Scripts/activate
复制代码
4. 编写主应用文件 (app.py)

WatchList目录下创建一个名为 app.py 的文件,并编写以下代码:
  1. from flask import Flask, render_template, url_for, redirect, request, flash
  2. from flask_sqlalchemy import SQLAlchemy
  3. import click
  4. app = Flask(__name__)
  5. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/watchlist'
  6. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  7. app.secret_key = 'your_secret_key'  # 用于闪现消息
  8. db = SQLAlchemy(app)
  9. # 创建数据库命令
  10. @app.cli.command()
  11. def forge():
  12.     """Generate fake data."""
  13.     db.create_all()
  14.     name = 'BrokenOfViolet'
  15.     movies = [
  16.         {'title': 'My Neighbor Totoro', 'year': '1988'},
  17.         {'title': 'Dead Poets Society', 'year': '1989'},
  18.         {'title': 'A Perfect World', 'year': '1993'},
  19.         {'title': 'Leon', 'year': '1994'},
  20.         {'title': 'Mahjong', 'year': '1996'},
  21.         {'title': 'Swallowtail Butterfly', 'year': '1996'},
  22.         {'title': 'King of Comedy', 'year': '1999'},
  23.         {'title': 'Devils on the Doorstep', 'year': '1999'},
  24.         {'title': 'WALL-E', 'year': '2008'},
  25.         {'title': 'The Pork of Music', 'year': '2012'},
  26.     ]
  27.     user = User(username=name, password='password123')  # 设定一个默认密码
  28.     db.session.add(user)
  29.     for m in movies:
  30.         movie = Movie(title=m['title'], year=m['year'])
  31.         db.session.add(movie)
  32.     db.session.commit()
  33.     click.echo('Done.')
  34. # 数据库模型
  35. class User(db.Model):
  36.     username = db.Column(db.String(20), primary_key=True)
  37.     password = db.Column(db.String(20))
  38. class Movie(db.Model):
  39.     id = db.Column(db.Integer, primary_key=True)
  40.     title = db.Column(db.String(60))
  41.     year = db.Column(db.String(4))
  42. # 主页路由
  43. @app.route('/')
  44. def index():
  45.     user = User.query.first()  # 修复此处变量名
  46.     movies = Movie.query.all()
  47.     return render_template("index.html", user=user, movies=movies)
  48. # 404 错误处理路由
  49. @app.errorhandler(404)
  50. def page_not_found(e):
  51.     user = User.query.first()
  52.     return render_template('404.html', user=user), 404
  53. # 登录路由
  54. @app.route('/login', methods=['GET', 'POST'])
  55. def login():
  56.     if request.method == 'POST':
  57.         username = request.form['username']
  58.         password = request.form['password']
  59.         user = User.query.filter_by(username=username).first()
  60.         # 比对用户输入的密码和数据库中存储的密码
  61.         if user and user.password == password:
  62.             flash('Login successful!', 'success')
  63.             return redirect(url_for('index'))  # 假设登录成功后重定向到index
  64.         else:
  65.             flash('Invalid username or password.', 'danger')
  66.     return render_template('login.html')
  67. if __name__ == '__main__':
  68.     app.run(debug=True)
复制代码
  1.  
复制代码
5. 创建 HTML 模板文件



  • 主页templates/index.html
 在 templates 目录中创建一个名为 index.html 的文件,编写一个简单的 HTML 页面:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="utf-8">
  5.     <link rel="stylesheet" href="{{url_for('static',filename='style.css')}}" type="text/css">
  6.     <title>{{ name }}'s Watchlist</title>
  7. </head>
  8. <body>
  9.     <h2>{{ name }}'s Watchlist
  10.         <img alt="Avatar" class="avator" src="{{url_for('static',filename='images/avatar.png')}}">
  11.     </h2>
  12.     {# 使用 length 过滤器获取 movies 变量的长度 #}
  13.     <p>{{ movies|length }} Titles</p>
  14.     <ul class="movie-list">
  15.         {% for movie in movies %}  {# 迭代 movies 变量 #}
  16.         <li>{{ movie.title }} - {{ movie.year }}</li>  {# 等同于 movie['title'] #}
  17.         {% endfor %}  {# 使用 endfor 标签结束 for 语句 #}
  18.     </ul>
  19.     <img alt="Totoro" class="totoro" src="{{url_for('static',filename='images/totoro.gif')}}"
  20. </body>
  21. </html>
复制代码


  • 登岸界面templates/login.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>Login</title>
  8.     <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  9. </head>
  10. <body>
  11.     <div class="login-container">
  12.         <h2>Login</h2>
  13.         {% with messages = get_flashed_messages(with_categories=true) %}
  14.           {% if messages %}
  15.             <ul class="flashes">
  16.               {% for category, message in messages %}
  17.                 <li class="{{ category }}">{{ message }}</li>
  18.               {% endfor %}
  19.             </ul>
  20.           {% endif %}
  21.         {% endwith %}
  22.         <form method="post" action="{{ url_for('login') }}">
  23.             <div class="input-group">
  24.                 <label for="username">Username</label>
  25.                 <input type="text" id="username" name="username" required>
  26.             </div>
  27.             <div class="input-group">
  28.                 <label for="password">Password</label>
  29.                 <input type="password" id="password" name="password" required>
  30.             </div>
  31.             <button type="submit">Login</button>
  32.         </form>
  33.     </div>
  34. </body>
  35. </html>
复制代码
6. 创建静态文件 (static/style.css)

static 目录中创建一个名为 style.css 的文件,添加一些简单的 CSS 样式:
  1. /* 页面整体 */
  2. body {
  3.     font-family: Arial, sans-serif;
  4.     background-color: #f0f0f0;
  5.     display: flex;
  6.     justify-content: center;
  7.     align-items: center;
  8.     height: 100vh;
  9.     margin: 0;
  10. }
  11. /* 页脚 */
  12. footer {
  13.     color: #888;
  14.     margin-top: 15px;
  15.     text-align: center;
  16.     padding: 10px;
  17. }
  18. /* 头像 */
  19. .avatar {
  20.     width: 40px;
  21. }
  22. /* 电影列表 */
  23. .movie-list {
  24.     list-style-type: none;
  25.     padding: 0;
  26.     margin-bottom: 10px;
  27.     box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
  28. }
  29. .movie-list li {
  30.     padding: 12px 24px;
  31.     border-bottom: 1px solid #ddd;
  32. }
  33. .movie-list li:last-child {
  34.     border-bottom:none;
  35. }
  36. .movie-list li:hover {
  37.     background-color: #f8f9fa;
  38. }
  39. /* 龙猫图片 */
  40. .totoro {
  41.     display: block;
  42.     margin: 0 auto;
  43.     height: 100px;
  44. }
  45. .login-container {
  46.     background-color: white;
  47.     padding: 20px;
  48.     border-radius: 10px;
  49.     box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  50.     width: 300px;
  51.     text-align: center;
  52. }
  53. h2 {
  54.     margin-bottom: 20px;
  55. }
  56. .input-group {
  57.     margin-bottom: 15px;
  58.     text-align: left;
  59. }
  60. .input-group label {
  61.     display: block;
  62.     margin-bottom: 5px;
  63. }
  64. .input-group input {
  65.     width: 100%;
  66.     padding: 8px;
  67.     box-sizing: border-box;
  68. }
  69. button {
  70.     width: 100%;
  71.     padding: 10px;
  72.     background-color: #007BFF;
  73.     color: white;
  74.     border: none;
  75.     border-radius: 5px;
  76.     cursor: pointer;
  77.     font-size: 16px;
  78. }
  79. button:hover {
  80.     background-color: #0056b3;
  81. }
  82. .flashes {
  83.     list-style-type: none;
  84.     padding: 0;
  85. }
  86. .flashes li {
  87.     padding: 10px;
  88.     margin-bottom: 10px;
  89.     border-radius: 5px;
  90. }
  91. .flashes li.success {
  92.     background-color: #d4edda;
  93.     color: #155724;
  94. }
  95. .flashes li.danger {
  96.     background-color: #f8d7da;
  97.     color: #721c24;
  98. }
复制代码
 
6. 运行应用

在终端中,导航到 WatchList 目录并运行应用。由于在app.py中界说了forge函数用于提交数据,以是进行如下操作:
  1. flask forge
复制代码
末了直接运行 app.py 或者执行 flask run

 
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莫张周刘王

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表