Chatgpt
Backend ใช้ SQLite เพื่อ store – user credentials securely
และให้ RESTful APIs – สำหรับ registration and login
- Install Dependencies
มีทั้ง Flask and SQLite installed:
pip install Flask Flask-SQLAlchemy
- Create the Flask Backend
Folder Structure
backend/
│-- app.py
└-- users.db (SQLite database will be created automatically)
app.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# User model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(256), nullable=False)
# Initialize the database
with app.app_context():
db.create_all()
# Route for user registration
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({'message': 'Please provide both username and password'}), 400
hashed_password = generate_password_hash(password)
if User.query.filter_by(username=username).first():
return jsonify({'message': 'Username already exists'}), 400
new_user = User(username=username, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User registered successfully'}), 201
# Route for user login
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({'message': 'Please provide both username and password'}), 400
user = User.query.filter_by(username=username).first()
if user and check_password_hash(user.password, password):
return jsonify({'message': 'Login successful'}), 200
else:
return jsonify({'message': 'Invalid credentials'}), 401
# Run the server
if __name__ == '__main__':
app.run(debug=True)
3. Run the Backend
In the terminal, navigate to the backend folder and run:
python app.py
The server will start at http://127.0.0.1:5000.
4. iOS Swift Code to Connect to the Backend
Register Function in Swift
import UIKit
func registerUser(username: String, password: String) {
let url = URL(string: "http://127.0.0.1:5000/register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: String] = [
"username": username,
"password": password
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
if let data = data, let responseString = String(data: data, encoding: .utf8) {
print("Response: \(responseString)")
}
}
task.resume()
}
Login Function in Swift
func loginUser(username: String, password: String) {
let url = URL(string: "http://127.0.0.1:5000/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: String] = [
"username": username,
"password": password
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
if let data = data, let responseString = String(data: data, encoding: .utf8) {
print("Response: \(responseString)")
}
}
task.resume()
}
- Calling These Functions in Your iOS App
You can call these functions when a user taps the Register or Login button:
// Example usage for registration
registerUser(username: "testuser", password: "password123")
// Example usage for login
loginUser(username: "testuser", password: "password123")
- CORS Handling (Optional)
If you encounter CORS (Cross-Origin Resource Sharing) issues when making requests from your iOS app to the Flask backend, install and configure the Flask-CORS package.
Install Flask-CORS
pip install Flask-CORS
Update app.py
Add the following import and enable CORS:
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Enable CORS for all routes
- Testing the Backend with curl
Register a User
curl -X POST http://127.0.0.1:5000/register -H "Content-Type: application/json" -d '{"username": "testuser", "password": "password123"}'
Login a User
curl -X POST http://127.0.0.1:5000/login -H "Content-Type: application/json" -d '{"username": "testuser", "password": "password123"}'
Security อันนี้ใช้เพียง plain-text passwords for simplicity.
แต่ real world จะใช้ hash passwords and use secure communication (HTTPS).
Database: ถ้าทำเพื่ production จริงๆ จะใช้ PostgreSQL or MySQL.
Error Handling: ให้ Add – Error handling , validation เพื่อให้ใช้งานได้ดีขึ้น
อันนี้ใช้ SQLite เพื่อ demon เพราะ
– Lightweight: เป็น serverless, และ self-contained database engine , ง่ายต่อการ setup and require minimal config
– built-in มาพร้อม python – ไม่ต้อง install db server เพิ่ม – เพื่อให้ได้ quick prototyping , small application
– ง่ายในการเข้าใจ CRUD (Create, Read, Update, Delete) – operation and interaction
– develop , buildign and testing small application
– หลายๆ mobile apps – ทั้ง iOS ,Android – ใช้ SQLite เพื่อ local storage
– สามารถใช้ใน single-user application – app ไม่ได้ต้องการ concurrent multiuser access
กรณีไม่ใช่ SQLite เช่น
Large-scale Applications: มี large datasets , high transaction volume -> แนะนำ PostgreSQL or MySQL
Multi-user Access: SQLite มี limited concurrent write capability – ไม่เหมาะกับ multiuser system
scalability ก็ไม่เหมาะ , พวกนี้แนะนำ PostgreSQL, MySQL, or MongoDB.
Upgrading to PostgreSQL
จาก Flask app ใช้ PostgreSQL แทน SQLite ให้ทำต่อไปนี้
Install PostgreSQL and psycopg2:
pip install psycopg2-binary
Update the Database Configuration in app.py:
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:password@localhost/dbname'
Run Database Migrations:
flask db init
flask db migrate -m "Initial migration."
flask db upgrade
