我想使用flutter和python的flask框架来实现登陆和注册功能,flutter负责设计登陆和注册表单的页面,flask框架作为后端来处理前端发送表单的数据
那么,flask框架需要怎么设计,在获取前端表单的数据中是不是需要token和session的玩意,是必须要的吗。接着flask拿到数据后去mysql数据库查找是否符合,如果成功的话,flutter前端应该要怎么跳转到首页,是得到flask发送的成功结果后就路由跳转吗?要让flask设计api请求的东东吗,有没有参考例子。
我想使用flutter和python的flask框架来实现登陆和注册功能,flutter负责设计登陆和注册表单的页面,flask框架作为后端来处理前端发送表单的数据
那么,flask框架需要怎么设计,在获取前端表单的数据中是不是需要token和session的玩意,是必须要的吗。接着flask拿到数据后去mysql数据库查找是否符合,如果成功的话,flutter前端应该要怎么跳转到首页,是得到flask发送的成功结果后就路由跳转吗?要让flask设计api请求的东东吗,有没有参考例子。
要使用Flutter和Flask实现登录和注册功能,需要进行以下步骤:
Flask后端代码:
from flask import Flask, request
from flask_restful import Resource, Api
from flask_cors import CORS
import hashlib
import pymysql
app = Flask(__name__)
api = Api(app)
CORS(app)
conn = pymysql.connect(host='localhost', user='root', password='password', db='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
class Register(Resource):
def post(self):
data = request.json
username = data.get('username')
password = data.get('password')
hash_password = hashlib.sha256(password.encode()).hexdigest()
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username=%s', (username,))
result = cursor.fetchone()
if result:
return {'message': 'User already exists.'}, 400
cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, hash_password))
conn.commit()
return {'message': 'Registration successful.'}, 201
class Login(Resource):
def post(self):
data = request.json
username = data.get('username')
password = data.get('password')
hash_password = hashlib.sha256(password.encode()).hexdigest()
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username=%s AND password=%s', (username, hash_password))
result = cursor.fetchone()
if not result:
return {'message': 'Invalid credentials.'}, 401
return {'message': 'Login successful.'}, 200
api.add_resource(Register, '/register')
api.add_resource(Login, '/login')
if __name__ == '__main__':
app.run(debug=True)
Flutter前端代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class RegisterScreen extends StatefulWidget {
@override
_RegisterScreenState createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen> {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
Future<void> _register() async {
final response = await http.post(
Uri.parse('http://localhost:5000/register'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'username': _usernameController.text,
'password': _passwordController.text,
}),
);
if (response.statusCode == 201) {
Navigator.pushReplacementNamed(context, '/home');
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(jsonDecode(response.body)['message'])),
);