mirror of
https://github.com/Llloooggg/TextSouls.git
synced 2026-03-06 04:26:23 +03:00
backend+ telegram: регистрация переведена на классы
This commit is contained in:
@@ -1,8 +1,8 @@
|
|||||||
"""empty message
|
"""empty message
|
||||||
|
|
||||||
Revision ID: 226bb7e77b6b
|
Revision ID: 8f02337dbef0
|
||||||
Revises:
|
Revises:
|
||||||
Create Date: 2022-11-17 22:55:34.747233
|
Create Date: 2022-11-18 17:37:55.798611
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from alembic import op
|
from alembic import op
|
||||||
@@ -10,7 +10,7 @@ import sqlalchemy as sa
|
|||||||
|
|
||||||
|
|
||||||
# revision identifiers, used by Alembic.
|
# revision identifiers, used by Alembic.
|
||||||
revision = '226bb7e77b6b'
|
revision = '8f02337dbef0'
|
||||||
down_revision = None
|
down_revision = None
|
||||||
branch_labels = None
|
branch_labels = None
|
||||||
depends_on = None
|
depends_on = None
|
||||||
@@ -19,15 +19,13 @@ depends_on = None
|
|||||||
def upgrade():
|
def upgrade():
|
||||||
# ### commands auto generated by Alembic - please adjust! ###
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
op.create_table('users',
|
op.create_table('users',
|
||||||
sa.Column('id', sa.Integer(), nullable=False),
|
sa.Column('id', sa.Integer(), autoincrement=False, nullable=False),
|
||||||
sa.Column('tg_id', sa.Integer(), nullable=False),
|
|
||||||
sa.Column('first_name', sa.String(length=255), nullable=True),
|
sa.Column('first_name', sa.String(length=255), nullable=True),
|
||||||
sa.Column('last_name', sa.String(length=255), nullable=True),
|
sa.Column('last_name', sa.String(length=255), nullable=True),
|
||||||
sa.Column('username', sa.String(length=255), nullable=False),
|
sa.Column('username', sa.String(length=255), nullable=False),
|
||||||
sa.Column('registered_on', sa.DateTime(), nullable=False),
|
sa.Column('registered_on', sa.DateTime(), nullable=False),
|
||||||
sa.Column('is_admin', sa.Boolean(), nullable=False),
|
sa.Column('is_admin', sa.Boolean(), nullable=False),
|
||||||
sa.PrimaryKeyConstraint('id'),
|
sa.PrimaryKeyConstraint('id')
|
||||||
sa.UniqueConstraint('tg_id')
|
|
||||||
)
|
)
|
||||||
# ### end Alembic commands ###
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
@@ -16,6 +16,7 @@ MarkupSafe==2.1.1
|
|||||||
pycparser==2.21
|
pycparser==2.21
|
||||||
PyMySQL==1.0.2
|
PyMySQL==1.0.2
|
||||||
SQLAlchemy==1.4.44
|
SQLAlchemy==1.4.44
|
||||||
|
SQLAlchemy-serializer==1.4.1
|
||||||
Werkzeug==2.2.2
|
Werkzeug==2.2.2
|
||||||
WTForms==3.0.1
|
WTForms==3.0.1
|
||||||
zipp==3.10.0
|
zipp==3.10.0
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ admin = Admin(name="TextSouls")
|
|||||||
with open("textsouls/config.json") as config_file:
|
with open("textsouls/config.json") as config_file:
|
||||||
config_data = json.load(config_file)
|
config_data = json.load(config_file)
|
||||||
|
|
||||||
main_settings = config_data["main_settings"]
|
main_settings = config_data["MAIN_SETTINGS"]
|
||||||
app.config.update(main_settings)
|
app.config.update(main_settings)
|
||||||
|
|
||||||
db_settings = config_data["db_settings"]
|
db_settings = config_data["DB_SETTINGS"]
|
||||||
app.config.update(db_settings)
|
app.config.update(db_settings)
|
||||||
|
|
||||||
admin.init_app(app)
|
admin.init_app(app)
|
||||||
|
|||||||
@@ -7,4 +7,12 @@ from textsouls.models import User
|
|||||||
|
|
||||||
ts_admin = Blueprint("ts_admin", __name__)
|
ts_admin = Blueprint("ts_admin", __name__)
|
||||||
|
|
||||||
admin.add_view(ModelView(User, db.session))
|
|
||||||
|
class AdminView(ModelView):
|
||||||
|
def __init__(self, model, *args, **kwargs):
|
||||||
|
self.column_list = [c.key for c in model.__table__.columns]
|
||||||
|
self.form_columns = self.column_list
|
||||||
|
super(AdminView, self).__init__(model, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
admin.add_view(AdminView(User, db.session))
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"main_settings": {
|
"MAIN_SETTINGS": {
|
||||||
"SECRET_KEY": "some-very-secret-key",
|
"SECRET_KEY": "some-very-secret-key",
|
||||||
"SQLALCHEMY_TRACK_MODIFICATIONS": false
|
"SQLALCHEMY_TRACK_MODIFICATIONS": false
|
||||||
},
|
},
|
||||||
"db_settings": {
|
"DB_SETTINGS": {
|
||||||
"SQLALCHEMY_DATABASE_URI": "mysql+pymysql://ownername:pass@localhost/textsouls"
|
"SQLALCHEMY_DATABASE_URI": "mysql+pymysql://ownername:pass@localhost/textsouls"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
from flask import Blueprint
|
from flask import Blueprint
|
||||||
from flask import request
|
from flask import request
|
||||||
|
from flask import jsonify
|
||||||
|
from flask.views import MethodView
|
||||||
|
|
||||||
from . import db
|
from . import db
|
||||||
from textsouls.models import User
|
from textsouls.models import User
|
||||||
@@ -7,34 +9,67 @@ from textsouls.models import User
|
|||||||
main = Blueprint("main", __name__)
|
main = Blueprint("main", __name__)
|
||||||
|
|
||||||
|
|
||||||
@main.route("/")
|
class ItemAPI(MethodView):
|
||||||
def index():
|
init_every_request = False
|
||||||
return "Nice!", 200
|
|
||||||
|
|
||||||
|
def __init__(self, model):
|
||||||
|
self.model = model
|
||||||
|
|
||||||
@main.route("/registration", methods=["POST"])
|
def _get_item(self, id):
|
||||||
def registration():
|
return self.model.query.get_or_404(id)
|
||||||
data = request.get_json()
|
|
||||||
|
|
||||||
tg_id = data.get("tg_id")
|
def get(self, id):
|
||||||
first_name = data.get("first_name")
|
item = self._get_item(id)
|
||||||
last_name = data.get("last_name")
|
return item.to_dict()
|
||||||
username = data.get("username")
|
|
||||||
|
|
||||||
existed_user = User.query.filter_by(tg_id=tg_id).first()
|
def patch(self, id):
|
||||||
|
item = self._get_item(id)
|
||||||
|
errors = self.validator.validate(item, request.json)
|
||||||
|
|
||||||
if not existed_user:
|
if errors:
|
||||||
new_user = User(
|
return jsonify(errors), 400
|
||||||
tg_id=tg_id,
|
|
||||||
first_name=first_name,
|
|
||||||
last_name=last_name,
|
|
||||||
username=username,
|
|
||||||
)
|
|
||||||
|
|
||||||
db.session.add(new_user)
|
item.update_from_json(request.json)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
return item.to_dict()
|
||||||
|
|
||||||
return {"created": True, "id": new_user.id}
|
def delete(self, id):
|
||||||
|
item = self._get_item(id)
|
||||||
|
db.session.delete(item)
|
||||||
|
db.session.commit()
|
||||||
|
return "", 200
|
||||||
|
|
||||||
else:
|
|
||||||
return {"created": False, "id": existed_user.id}
|
class ListAPI(MethodView):
|
||||||
|
init_every_request = False
|
||||||
|
|
||||||
|
def __init__(self, model):
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
def _get_item(self, id):
|
||||||
|
return self.model.query.filter_by(id=id).first()
|
||||||
|
|
||||||
|
def get(self):
|
||||||
|
items = self.model.query.all()
|
||||||
|
return jsonify([item.to_dict() for item in items])
|
||||||
|
|
||||||
|
def post(self):
|
||||||
|
|
||||||
|
item = self._get_item(request.json["id"])
|
||||||
|
|
||||||
|
if item:
|
||||||
|
return "Already exists!", 400
|
||||||
|
|
||||||
|
db.session.add(self.model(**request.json))
|
||||||
|
db.session.commit()
|
||||||
|
return "", 200
|
||||||
|
|
||||||
|
|
||||||
|
def register_api(app, model, name):
|
||||||
|
item = ItemAPI.as_view(f"{name}-item", model)
|
||||||
|
group = ListAPI.as_view(f"{name}-list", model)
|
||||||
|
app.add_url_rule(f"/{name}/<int:id>", view_func=item)
|
||||||
|
app.add_url_rule(f"/{name}/", view_func=group)
|
||||||
|
|
||||||
|
|
||||||
|
register_api(main, User, "users")
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from sqlalchemy_serializer import SerializerMixin
|
||||||
|
|
||||||
|
|
||||||
db = SQLAlchemy()
|
db = SQLAlchemy()
|
||||||
|
|
||||||
|
|
||||||
class User(db.Model):
|
class User(db.Model, SerializerMixin):
|
||||||
|
|
||||||
__tablename__ = "users"
|
__tablename__ = "users"
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
|
||||||
tg_id = db.Column(db.Integer, unique=True, nullable=False)
|
|
||||||
first_name = db.Column(db.String(255), nullable=True)
|
first_name = db.Column(db.String(255), nullable=True)
|
||||||
last_name = db.Column(db.String(255), nullable=True)
|
last_name = db.Column(db.String(255), nullable=True)
|
||||||
username = db.Column(db.String(255), nullable=False)
|
username = db.Column(db.String(255), nullable=False)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ with open("textsouls/config.json") as config_file:
|
|||||||
|
|
||||||
|
|
||||||
class Backend:
|
class Backend:
|
||||||
base_url = config_data["backend_settings"]["base_url"]
|
base_url = config_data["BACKEND_SETTINGS"]["BASE_URL"]
|
||||||
|
|
||||||
def post(self, relative_url, data):
|
def post(self, relative_url, data):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"main_settings": {
|
"MAIN_SETTINGS": {
|
||||||
"bot_token": "token-from-@BotFather"
|
"BOT_TOKEN": "token-from-@BotFather"
|
||||||
},
|
},
|
||||||
"backend_settings": {
|
"BACKEND_SETTINGS": {
|
||||||
"base_url": "http://localhost:5000"
|
"BASE_URL": "http://localhost:5000"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ from common import backend
|
|||||||
with open("textsouls/config.json") as config_file:
|
with open("textsouls/config.json") as config_file:
|
||||||
config_data = json.load(config_file)
|
config_data = json.load(config_file)
|
||||||
|
|
||||||
API_TOKEN = config_data["main_settings"]["bot_token"]
|
API_TOKEN = config_data["MAIN_SETTINGS"]["BOT_TOKEN"]
|
||||||
|
|
||||||
bot = Bot(token=API_TOKEN)
|
bot = Bot(token=API_TOKEN)
|
||||||
dp = Dispatcher(bot)
|
dp = Dispatcher(bot)
|
||||||
@@ -17,18 +17,20 @@ dp = Dispatcher(bot)
|
|||||||
async def start(message):
|
async def start(message):
|
||||||
tg_user = message.from_user
|
tg_user = message.from_user
|
||||||
ts_user = {
|
ts_user = {
|
||||||
"tg_id": tg_user.id,
|
"id": tg_user.id,
|
||||||
"first_name": tg_user.first_name,
|
"first_name": tg_user.first_name,
|
||||||
"last_name": tg_user.last_name,
|
"last_name": tg_user.last_name,
|
||||||
"username": tg_user.username,
|
"username": tg_user.username,
|
||||||
}
|
}
|
||||||
result = backend.post("/registration", ts_user)
|
result = backend.post("/users", ts_user)
|
||||||
if not result["error"] and result["response"].ok:
|
if not result["error"]:
|
||||||
data = json.loads(result["response"].text)
|
response_code = result["response"].status_code
|
||||||
if data["created"]:
|
if response_code == 200:
|
||||||
await message.reply("Добро пожаловать!")
|
await message.reply("Добро пожаловать!")
|
||||||
else:
|
elif response_code == 400:
|
||||||
await message.reply("Добро пожаловать! Снова")
|
await message.reply("Добро пожаловать! Снова")
|
||||||
|
else:
|
||||||
|
await message.reply("Что-то другое")
|
||||||
else:
|
else:
|
||||||
await message.reply("Упс! Что-то пошло не так")
|
await message.reply("Упс! Что-то пошло не так")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user