при GET запросе на Flask сервер получаю 404 Not Found: The requested URL was not found on the server
Есть самописный сервер на Flask с тремя функциями: добавить пользователя, отредактировать пользователя, посмотреть всех пользователей в связке с PostgreSQL. По какой-то причине работает только метод с добавлением новых пользователей, я вижу как они создаются в pgadmin, запрос POST на добавление отправляю через POSTMAN, но я не могу увидеть пользователей или отредактировать их. При запросе GET Postman возвращает: "error": "404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." Проверила, что HTTP-запрос отправляю правильно, он выдает 500 INTERNAL SERVER ERROR, если аргумент в виде пользователя забываю. Подскажите в чем, может быть проблема, я не могу определить даже куда смотреть. Код ниже или https://github.com/Bluefire137/DishDash
server.py
import threading
import configparser
from flask import Flask, request, jsonify, abort
from exception.exception import UserNotFoundException
from interaction.interactions import DbInteraction
class Server:
def __init__(self, host, port, db_host, db_port, user, password, db_name, rebuild_db=False):
self.host = host
self.port = port
self.db_interaction = DbInteraction(
host=db_host,
port=db_port,
user=user,
password=password,
db_name=db_name,
rebuild_db=True
)
self.app = Flask(__name__)
self.app.add_url_rule('/shutdown', view_func=self.shutdown)
self.app.add_url_rule('/', view_func=self.get_home)
self.app.add_url_rule('/home', view_func=self.get_home)
self.app.add_url_rule('/add_user_info', view_func=self.add_user_info, methods=['POST'])
self.app.add_url_rule('/get_user_info', view_func=self.get_user_info, methods=['GET'])
self.app.add_url_rule('/edit_user_info', view_func=self.edit_user_info, methods=['PUT'])
self.app.register_error_handler(404, self.page_not_found)
def page_not_found(self, err_description):
return jsonify(error=str(err_description)), 404
def run_server(self):
self.server = threading.Thread(target=self.app.run, kwargs={'host': self.host, 'port': self.port})
self.server.start()
return self.server
def shutdown_server(self):
request.get(f'http://{self.host}:{self.port}/shutdown')
def shutdown(self):
terminate_func = request.environ.get('werkzeug.server.shutdown')
if terminate_func:
terminate_func()
def get_home(self):
return 'Hello, api-server!'
def add_user_info(self):
request_body = dict(request.json)
username = request_body['username']
password = request_body['password']
email = request_body['email']
self.db_interaction.add_user_info(
username=username,
password=password,
email=email
)
return f'Success added {username}', 201
def get_user_info(self, username):
try:
user_info = self.db_interaction.get_user_info(username)
return user_info, 200
except UserNotFoundException:
abort(404, description='User not found')
def edit_user_info(self, username):
request_body = dict(request.json)
new_username = request_body['username']
new_password = request_body['password']
new_email = request_body['email']
self.db_interaction.edit_user_info(
username=username,
new_username=new_username,
new_password=new_password,
new_email=new_email
)
return f'Success!', 200
if __name__ == '__main__':
config = configparser.ConfigParser()
config.read('config.txt')
server_host = config['DEFAULT']['SERVER_HOST']
server_port = config['DEFAULT']['SERVER_PORT']
db_host = config['DEFAULT']['DB_HOST']
db_port = config['DEFAULT']['DB_PORT']
db_user = config['DEFAULT']['DB_USER']
db_password = config['DEFAULT']['DB_PASSWORD']
db_name = config['DEFAULT']['DB_NAME']
'''parser = argparse.ArgumentParser()
parser.add_argument('--config', type = str, dest = 'config')
args = parser.parse_args()
config = config_parser(args.config)
server_host = config['SERVER_HOST']
server_port = config['SERVER_PORT']'''
server = Server(
host=server_host,
port=server_port,
db_host=db_host,
db_port=db_port,
user=db_user,
password=db_password,
db_name=db_name
)
server.run_server()
Interactions.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from exception.exception import UserNotFoundException
from models.models import Base, User
class DbInteraction:
def __init__(self, host, port, user, password, db_name, rebuild_db=False):
self.engine = create_engine(f'postgresql+psycopg2://{user}:{password}@{host}:{port}/{db_name}')
if rebuild_db:
self.create_table_users()
self.create_table_dishes()
def create_table_users(self):
Base.metadata.create_all(self.engine)
def create_table_dishes(self):
Base.metadata.create_all(self.engine)
def add_user_info(self, username, email, password):
user = User(
username=username,
password=password,
email=email
)
Session = sessionmaker(bind=self.engine)
session = Session()
session.add(user)
session.commit()
return self.get_user_info(username)
def get_user_info(self, username):
Session = sessionmaker(bind=self.engine)
session = Session()
user = session.query(User).filter_by(username=username).first()
if user:
session.expire_all()
return {'username': user.username, 'email': user.email, 'password': user.password}
else:
raise UserNotFoundException('User not found!')
def edit_user_info(self, username, new_username=None, new_email=None, new_password=None):
Session = sessionmaker(bind=self.engine)
session = Session()
user = session.query(User).filter_by(username=username).first()
if user:
if new_username is not None:
user.username = new_username
if new_email is not None:
user.email = new_email
if new_password is not None:
user.password = new_password
session.commit()
return self.get_user_info(username if new_username is None else new_username)
else:
raise UserNotFoundException
if __name__ == '__main__':
db = DbInteraction(
host='127.0.0.1',
port=5432,
user='postgres',
password='ghbdtn137',
db_name='some_db',
rebuild_db=True)
models.py
from sqlalchemy import Column, Integer, ForeignKey, VARCHAR, UniqueConstraint
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
#Создание таблиц Users и Dishes
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
username = Column(VARCHAR(50), nullable=True)
password = Column(VARCHAR(300), nullable=False)
email = Column(VARCHAR(40))
UniqueConstraint(username, name='username')
UniqueConstraint(email, name='email')
class Dishes(Base):
__tablename__ = 'dishes'
id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
user_id = Column(Integer, ForeignKey(f'{User.__tablename__}.{User.id.name}'), nullable=False)
dish = Column(VARCHAR(100), nullable=True)
user = relationship('User', backref='dishes')
config.txt
[DEFAULT]
SERVER_HOST = 0.0.0.0
SERVER_PORT = 5005
DB_HOST = 127.0.0.1
DB_PORT = 5432
DB_USER = postgres
DB_PASSWORD = ghbdtn137
DB_NAME = some_db
exceptions.py
class UserNotFoundException(Exception):
pass