注册app文件
import json
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL
from flask_login import logout_user
import pymysql
from flask import Flask, render_template
from flask import Flask, jsonify
from flask import Flask, send_from_directory
from flask import Flask
from flask_cors import CORS
import requests
from flask import redirect
# 改密
# from flask_wtf import FlaskForm
# from wtforms import StringField, PasswordField, SubmitField
# from wtforms.validators import DataRequired, Length, EqualTo
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'topic'
mysql = MySQL(app)
# 区分大小写,且users位置也区分
users = []
# 钩子函数,每次打开第一件做的事情
@app.before_first_request
def load_users():
cursor = mysql.connection.cursor()
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
# users = []
for row in rows:
user = {'id': row[0], 'username': row[1], 'password': row[2]}
users.append(user)
cursor.close()
# app.config['USERS'] = users
# register.py['users'] = users
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
# 字典
users = [{'username': 'admin', 'password': 'asd123'}] # https://blog.csdn.net/weixin_36380516/article/details/80008602
@app.route("/register", methods=['GET', 'POST'])
def register():
if request.method == 'POST': # 为什么要写这个if判断是否POST方式。如果不加的话可能报错......因为网页跳转也在这个路由上实现
username = request.form.get("username") # POST方式
password = request.form.get("password")
repassword = request.form.get('repassword')
# 连接数据库
cursor = mysql.connection.cursor()
# 判断有无重名
for i in users:
if i['username'] == username:
return '用户名已被注册'
# 判断俩次密码是否一致
if password == repassword and password != '' and username != '':
user = {'username': username, 'password': password}
# 写入show
users.append(user)
# 下面三句是把信息写入数据库
cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, password))
mysql.connection.commit()
cursor.close()
return "注册成功"
return "俩次密码不一致,或未输入密码"
return render_template('register.html')
# @app.route('/search')
# def search():
# for i in users:
# if i['username'] == 'aa':
# return '用户名已被注册'
# return "未注册"
# @app.route('/weiboindex.html')
# def weiboindex():
# print(conn)
# # 从数据库中读取数据
# cursor = conn.cursor()
# cursor.execute('SELECT * FROM weibo')
# data = cursor.fetchall()
# # print(data)
# # # 获取查询结果
# cursor.close()
# # # 将数据传递给前台模板
# # return data[0]
# return render_template('weiboindex.html', data=data)
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
l_username = request.form.get("l_username")
l_password = request.form.get("l_password")
# try:
for i in users:
# if i['username'] != l_username:
# return "用户名未注册"
if i['username'] == l_username and i['password'] == l_password:
# return "登录成功"
print("login")
# return redirect('http://127.0.0.1:5000/weiboindex.html')
return render_template('weiboindex.html')
# return render_template('http://127.0.0.1:5000 ') #TemplateNotFound
if i['username'] == l_username and i['password'] != l_password:
return "密码输入错误"
# print(i, len(users))
return "用户名未注册"
return render_template('login.html')
@app.route('/show')
def show():
print(users[0]['username'])
json_str = json.dumps(users) # 将python数据结构转换为JSON
print(json_str)
return json_str
# 不同app泻在同文件
# CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}})
# conn = pymysql.connect(host='localhost',user='root',password='123456',database='topic',charset='utf8mb4',
# cursorclass=pymysql.cursors.DictCursor )
# if conn:
# print('数据库连接成功!')
# else:
# print('数据库连接失败!')
# app2 = Flask(__name__)
# @app2.route('/weiboindex.html')
# def weiboindex():
# print(conn)
# # 从数据库中读取数据
# cursor = conn.cursor()
# cursor.execute('SELECT * FROM weibo')
# data = cursor.fetchall()
# # print(data)
# # # 获取查询结果
# cursor.close()
# # # 将数据传递给前台模板
# # return data[0]
# return render_template('weiboindex.html', data=data)
# # resp = jsonify({'message': 'Welcome to somepage!'})
# # resp.headers['Access-Control-Allow-Origin'] = '*'
# # return resp
if __name__ == '__main__':
app.run(debug=True, port=8000,use_reloader=False)
# app2.run(debug=True, port=5000,use_reloader=False)
# app.run(debug=True, port=8000,use_reloader=False)
# if request.method == 'POST':
# username = request.form['username']
# password = request.form['password']
# cursor = mysql.connection.cursor()
# cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, password))
# mysql.connection.commit()
# cursor.close()
# return 'Successfully registered!'
# else:
# return render_template('register.html')
# 改密
# @app.route('/change_password', methods=['GET', 'POST'])
# @login_required
# def change_password():
# form = ChangePasswordForm()
# if form.validate_on_submit():
# if current_user.check_password(form.old_password.data):
# current_user.set_password(form.new_password.data)
# db.session.commit()
# return 'Your password has been updated.'
# else:
# return 'Invalid old password'
# return render_template('change_password.html', form=form)
# class User(UserMixin, db.Model):
# __tablename__ = 'users'
# id = db.Column(db.Integer, primary_key=True)
# username = db.Column(db.String(64), index=True, unique=True)
# password_hash = db.Column(db.String(128))
# def set_password(self, password):
# self.password_hash = generate_password_hash(password)
# def check_password(self, password):
# return check_password_hash(self.password_hash, password)
# 数据库改
# cursor = mysql.connection.cursor()
# cursor.execute('UPDATE users SET username = %s, password = %s WHERE id = %s', (username, password, user_id))
# mysql.connection.commit()
# cursor.close()
# 登出
# Flask-Login提供的 “logout_user” 函数,用户 ID 存储在 Flask-Login提供的 “current_user”,登出既删current_user
# @app.route('/logout')
# @login_required
# def logout():
# logout_user()
# return '你已登出.'
# 改密
# class ChangePasswordForm(FlaskForm):
# old_password = PasswordField('Old Password', validators=[DataRequired()])
# new_password = PasswordField('New Password', validators=[
# DataRequired(),
# Length(min=6, message='Password must be at least 6 characters.'),
# EqualTo('confirm_password', message='Passwords must match.')
# ])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired()])
# submit = SubmitField('Change Password')
后端app2文件
import pymysql
from flask import Flask, render_template
from flask import Flask, jsonify
from flask import Flask, send_from_directory
from flask import Flask
from flask_cors import CORS
import requests
app2 = Flask(__name__)
# 创建flask应用,__name__ 表示当前模块的名称。
# 连接 MySQL 数据库,注意修改数据库连接信息
# conn = pymysql.connect(host='localhost', user='root', password='123456', db='topic', charset='utf8mb4')
# 存储和处理特殊字符 如表情,应该使用 UTF-8MB4 而不是默认的 UTF-8
# @app.route('/home')
# 打开程序根目录=打开index。html=首页。 用户访问应用程序的根路径 / 时,Flask 会调用名为 index() 的函数来处理该请求。
# def home():
# 浏览器的同源策略(Same Origin Policy)
# 前端应用程序运行在 http://127.0.0.1:5500 域名下,而后台应用程序运行在 http://127.0.0.1:5000 域名下,因此浏览器会阻止前端应用程序发起跨域请求。
# 前端应用程序通常是在本地开发服务器中运行的,而后台应用程序通常是在 Flask、Django 或其他 Web 框架中运行的。这些 Web 框架通常会默认使用 5000 端口来监听 HTTP 请求。
# CORS(app)#允许所有跨域
CORS(app2, resources={r"/*": {"origins": "http://127.0.0.1:5500"}})
# 只允许本地
# CORS(app, resources={r"/*": {"origins": "http://localhost:5500"}})
# 用localhost就访问不了127.0.0.1。虽然 localhost 和 127.0.0.1 是同一个 IP,但却被视为不同的域名
# 创建数据库连接 # 返回字典类型的游标,方便操作
conn = pymysql.connect(host='localhost',user='root',password='123456',database='topic',charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor )
# 检查连接是否成功
if conn:
print('数据库连接成功!')
else:
print('数据库连接失败!')
@app2.route('/')
def index():
print(conn)
# 从数据库中读取数据
cursor = conn.cursor()
cursor.execute('SELECT * FROM weibo')
data = cursor.fetchall()
# print(data)
# # 获取查询结果
cursor.close()
# # 将数据传递给前台模板
# return data[0]
return render_template('weiboindex.html', data=data)
# import tkinter as tk
# from tkinter import *
# from tkinter import messagebox
# win1=tk.Tk()
# win1.title('MY main')#添加窗体名称
# win1.geometry('670x470')#设置窗体大小
# def msgbox():
# messagebox.showinfo("窗体名", "Python")
# Button(win1, text="按钮1").pack()#添加第一个按钮
# Button(win1, text="弹出对话框", command=msgbox).pack()#添加第二个按钮
# win1.mainloop()
# @app.route('/data')
# def get_data():
# r = requests.get('http://127.0.0.1:5000')
# data = r.json()
# return jsonify(data)
# from flask import abort
# @app.route('/')
# def index():
# try:
# cursor = conn.cursor()
# cursor.execute('SELECT * FROM weibo')
# data = cursor.fetchall()
# cursor.close()
# return render_template('index.html', data=data)
# except Exception as e:
# abort(500, f"An error occurred: {str(e)}")
# app = Flask(__name__)
# <script src="{{ url_for('static', filename='index.js') }}"></script>报错解决方法
# @app.route('/static/<path:path>')
# def serve_static(path):
# return send_from_directory('static', path, mimetype='text/javascript')
# 手写的数据传送前端
# @app.route('/data')
# # @app.route('/http://127.0.0.1:5500/data')
# def get_data():
# # 从数据库或其他数据源获取数据
# data = [{'rid': 19, '用户名称': '生椰拿小林', '微博等级': '普通用户', '微博内容': '#疫情#\n难得,食堂拆除挡板了', '微博转发量': 0, '微博评论量': 0, '微博点赞': 0, '发布时间': '3-28 18:11', '搜索关键词': '#疫情#', '话题名称': '#疫情#', '话题讨论数': '今日阅读1.2万', '话题阅读数': '今日讨论244'},
# {'rid': 19, '用户名称': '生椰拿小林', '微博等级': '普通用户', '微博内容': '#疫情#\n难得,食堂拆除挡板了', '微博转发量': 0, '微博评论量': 0, '微博点赞': 0, '发布时间': '3-28 18:11', '搜索关键词': '#疫情#', '话题名称': '#疫情#', '话题讨论数': '今日阅读1.2万', '话题阅读数': '今日讨论244'}]
# return jsonify(data) # 返回JSON格式的响应
# def data():
# return jsonify({'message': 'Hello, World!'})
# 如后台转json文件正确的话,/data会显示json
if __name__ == '__main__':
# app.run()
# app.run(port=5500) #后端改为5500
app2.run(debug=True)
# print(f"Flask app is running on http://127.0.0.1:{app.config['PORT']}")
# 如果当前脚本为主程序,则会执行此语句,启动应用程序并监听本地的默认端口 5000。
# 没有这个判断语句,那么无论这个脚本是被其他程序导入还是直接执行,都会执行 app.run() 函数,这可能会导致一些问题。
# @app.route('/data')
# def get_data():
# data = {'foo': 'bar'}
# return jsonify(data)
# import pandas as pd
# from sqlalchemy import create_engine
# # 爬取微博数据的代码,已省略
# # 将 xls 中的数据写入到 MySQL 数据库中
# df = pd.read_excel('table.xls')
# engine = create_engine('mysql+pymysql://root:password@localhost:3306/database')
# df.to_sql(name='weibo', con=engine, if_exists='replace', index=False)