forked from milehigh-world/milehigh-club
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This code sets up a basic Flask app with a /register endpoint for user registration. It validates the input data, creates a new user account, and stores it in a SQLite database. We’re using SQLAlchemy to interact with the database.
- Loading branch information
1 parent
35fcd70
commit c2e7d4e
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
from flask import Flask, request, jsonify | ||
from sqlalchemy import create_engine, Column, String, Integer | ||
from sqlalchemy.ext.declarative import declarative_base | ||
from sqlalchemy.orm import sessionmaker | ||
from sqlalchemy.exc import IntegrityError | ||
|
||
# Initialize Flask app | ||
app = Flask(__name__) | ||
|
||
# Database configuration | ||
db_uri = 'sqlite:///milehigh.db' | ||
engine = create_engine(db_uri) | ||
Base = declarative_base() | ||
|
||
# Define User model | ||
class User(Base): | ||
__tablename__ = 'users' | ||
id = Column(Integer, primary_key=True) | ||
username = Column(String(50), unique=True, nullable=False) | ||
email = Column(String(100), unique=True, nullable=False) | ||
password = Column(String(100), nullable=False) | ||
|
||
# Create database tables | ||
Base.metadata.create_all(engine) | ||
|
||
# Function to handle user registration | ||
@app.route('/register', methods=['POST']) | ||
def register_user(): | ||
data = request.json | ||
username = data.get('username') | ||
email = data.get('email') | ||
password = data.get('password') | ||
|
||
# Validate inputs | ||
if not username or not email or not password: | ||
return jsonify({'error': 'All fields are required'}), 400 | ||
|
||
# Create user account | ||
try: | ||
user = User(username=username, email=email, password=password) | ||
Session = sessionmaker(bind=engine) | ||
session = Session() | ||
session.add(user) | ||
session.commit() | ||
session.close() | ||
return jsonify({'message': 'User registration successful'}), 201 | ||
except IntegrityError: | ||
return jsonify({'error': 'Username or email already exists'}), 400 | ||
|
||
if __name__ == '__main__': | ||
app.run(debug=True) |