I'm new to Flask and Python and I'm struggling with circular imports with my auth routes and user routes. I can successfully access other API endpoints except my auth_routes endpoints. How can I fix this issue?
My file structure is:
app/
|backend/
|models/
|user.py
|etc...
|routes/
|auth_routes
|etc...
|app.py
|frontend/
...
My auth_routes imports from app and models.user My user.py imports db from app
My auth_routes:
from flask import Blueprint, request, jsonify, abort
from flask_login import login_user, logout_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
from datetime import datetime, timedelta
from app import db, app
from models import User
auth_routes = Blueprint('auth_routes', __name__)
@auth_routes.route('/signup', methods=['POST'])
def signup():
print(request)
data = request.get_json()
print(data)
user_exists = User.query.filter_by(email=data['email']).first()
if user_exists:
abort(400)
if len(data['password']) < 8:
return jsonify({'message': 'Password must be at least 8 characters long'}), 400
hashed_password = generate_password_hash(data['password'], method='sha256')
new_user = User(email=data['email'], password=hashed_password,
first_name=data['first_name'], last_name=data['last_name'])
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User registered successfully'}), 201
@auth_routes.route('/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(email=data['email']).first()
if user and check_password_hash(user.password, data['password']):
token = jwt.encode({
'user_id': user.id,
'exp': datetime.utcnow() + timedelta(days=1)
}, app.config['SECRET_KEY'], algorithm='HS256')
return jsonify({'token': token})
return jsonify({'message': 'Invalid credentials'}), 401
My app.py:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from functools import wraps
import jwt
from routes.auth_routes import auth_routes
from routes.user_routes import user_routes
from routes.event_routes import event_routes
from routes.artist_routes import artist_routes
from routes.venue_routes import venue_routes
from routes.genre_routes import genre_routes
from models.user import User
app = Flask(__name__)
CORS(app, origins=["http://localhost:3000"], method=["GET", "POST", "PUT", "DELETE"], allow_headers=["Content-Type", "Authorization"])
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/ticketmaster_clone'
app.config['SECRET_KEY'] = 'secretkey'
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'message': 'Token is missing'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
current_user = User.query.get(data['user_id'])
except:
return jsonify({'message': 'Token is invalid'}), 401
return f(current_user, *args, **kwargs)
return decorated
db = SQLAlchemy(app)
app.register_blueprint(auth_routes)
app.register_blueprint(user_routes)
app.register_blueprint(event_routes)
app.register_blueprint(artist_routes)
app.register_blueprint(venue_routes)
app.register_blueprint(genre_routes)
migrate = Migrate(app, db)
if __name__ == '__main__':
app.run(debug=True, port=8080)
I've used Postman to check the endpoints, they work except signup and login. I've also tried signing up through the client side and I get this:
signup:1 Access to XMLHttpRequest at 'http://localhost:8080/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.