Commit ac6c4217 authored by Eliss-good's avatar Eliss-good
Browse files

natasha

parent 6bc50873
......@@ -56,6 +56,17 @@ def all_advertisments():
api_all_adv = AdvertisementSchema(many=True)
return api_all_adv.dump(data_query)
def filter_advertisments(id_adv=None):
data_query = _base_query()
if id_adv is not None:
data_query = data_query.filter(Advertisement.id == id_adv)
api_all_adv = AdvertisementSchema(many=True)
return api_all_adv.dump(data_query)
def indexes_advertisments(indexes: list = None):
data_query = _base_query()
......
......@@ -4,6 +4,8 @@ from functools import wraps
from flask import jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
from routers.all_dataclasses import EntryDate
from models.all_models import Users
......@@ -22,9 +24,9 @@ def admin_required():
return wrapper
def login(LoginData):
username = LoginData.login
password = LoginData.password
def login(Entry: EntryDate):
username = Entry.login
password = Entry.password
query_user = db.session.query(Users)
query_user = query_user.filter(Users.login == username).first()
......@@ -34,6 +36,8 @@ def login(LoginData):
access_token = create_access_token(
"admin_user", additional_claims={"is_administrator": True}
)
return access_token
return {'access_token':access_token,
'user_id':query_user.id,
'role': query_user.role}
else:
return jsonify({"msg": "Bad username or password"}), 401
return {"msg": "Bad username or password"}
from web_setting import flask_app, ma
from models.all_models import Customers, Users
from models.all_models import Customers, Users, TagsUsers, Tags
from api.api_users import UsersSchema
from api.api_users import UsersSchema, _base_query_user_tag
class CustomersSchema(ma.SQLAlchemyAutoSchema):
......@@ -9,5 +9,44 @@ class CustomersSchema(ma.SQLAlchemyAutoSchema):
model = Customers
load_instance = True
include_relationships = True
exclude = ['customer_approve']
connect_users = ma.Nested(UsersSchema(exclude=('users_emp', 'users_cus', 'password','id', )))
\ No newline at end of file
connect_users = ma.Nested(UsersSchema(exclude=('users_emp', 'users_cus', 'password','id', )))
def _base_query():
return Customers.query
def all_customers():
query_data = _base_query()
api_customers = CustomersSchema(many=True)
return api_customers.dump(query_data)
def filter_customers(login=None,
tags: list = None,
user_id: list = []):
query_data = _base_query()
api_customers = CustomersSchema(many=True)
if tags is not None:
print(_base_query_user_tag().all())
query_tags_us = _base_query_user_tag()
query_tags_us = query_tags_us.distinct(TagsUsers.user_id)
query_tags_us = query_tags_us.filter(Tags.tag_name.in_(tags)).all()
user_id = []
for element in query_tags_us:
users_ids.append(element[0])
if user_id is not None:
query_data = query_data.filter(Customers.user_id.in_(user_id))
if login is not None:
query_data = query_data.join(Users)
query_data = query_data.filter(Users.login == login)
api_customers = CustomersSchema(many=True)
return api_customers.dump(query_data)
\ No newline at end of file
from web_setting import flask_app, ma, db
from models.all_models import Users, TagsUsers
from models.all_models import Users, TagsUsers, Tags
from api.api_tags import TagsGlobalSchema
......@@ -24,6 +24,9 @@ class UsersSchema(ma.SQLAlchemyAutoSchema):
def _base_query():
return db.session.query(Users)
def _base_query_user_tag():
return db.session.query(TagsUsers.user_id, TagsUsers.tags_id, Tags.tag_name).join(Tags)
#
def all_users():
data_query = _base_query()
......
import email
from web_setting import flask_app, db
from models.all_models import Users, Employer
from models.all_models import Users, Employer, Customers, TagsUsers, ClickHistory
from werkzeug.security import generate_password_hash, check_password_hash
from routers.all_dataclasses import EntryDate, TagsIndex
from typing import List
def add_new_users(RegisterData):
def add_new_users(RegisterData: EntryDate):
hash_password = generate_password_hash(RegisterData.password)
new_users = Users(
new_name=RegisterData.user_name,
......@@ -14,13 +16,33 @@ def add_new_users(RegisterData):
new_email=RegisterData.email
)
db.session.add(new_users)
db.session.commit()
if RegisterData.role == 0:
new_emp = Employer(user_id=new_users.id)
db.session.add(new_emp)
new_con = Employer(user_id=new_users.id, new_discription=RegisterData.discription)
db.session.add(new_con)
db.session.commit()
db.session.add(new_users)
db.session.commit()
elif RegisterData.role == 1:
new_con = Customers(user_id=new_users.id, coords=RegisterData.coordinat)
db.session.add(new_con)
db.session.commit()
return "successful registration"
def add_new_click(NewClick: TagsIndex):
clicks_queue = []
for one_click in NewClick.tags_id:
new_click = ClickHistory(user_id=NewClick.index_connect, tags_id=one_click)
clicks_queue.append(new_click)
db.session.add_all(clicks_queue)
db.session.commit()
""" 1) Подписка на комьюнити и инскрт новых коммьюнити
2) Создание новых объявлений
3) обработка друзей и лоби"""
......@@ -30,6 +30,7 @@ class Users(db.Model):
def __init__(self, new_name, new_login, password, new_email, role=ROLE_EMPLOYER):
self.user_name = new_name
self.role = role
self.login = new_login
self.password = password
self.email = new_email
......@@ -71,21 +72,12 @@ class Community(db.Model):
__tablename__ = 'community'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
community_name = db.Column(db.String)
community_description = db.Column(db.Text)
def __init__(self, new_community_name, new_customer_id):
self.community_name = new_community_name
self.customer_id = new_customer_id
class TagsCommunity(db.Model):
__tablename__ = 'tags_community'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
tags_id = db.Column(db.Integer, db.ForeignKey('tags.id'))
connect_tags = db.relationship('Tags', backref='tags_community')
community_id = db.Column(db.Integer, db.ForeignKey('community.id'))
connect_community = db.relationship('Community', backref='self_community')
def __init__(self, new_community_name, new_community_description):
self.community_name = new_community_name
self.community_description = new_community_description
class Customers(db.Model):
......@@ -100,7 +92,8 @@ class Customers(db.Model):
community_id = db.Column(db.Integer, db.ForeignKey('community.id'))
connect_com = db.relationship('Community', backref='community_cus')
def __init__(self, coords, points_amount):
def __init__(self, coords, user_id, points_amount = 0):
self.user_id = user_id
self.coordinates = coords
self.points = points_amount
......@@ -126,12 +119,13 @@ default_confirmed_status = False
class Advertisement(db.Model):
__tablename__ = 'advertisement'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
confirmed = db.Column(db.Integer)
adv_name = db.Column(db.String)
time_event = db.Column(db.Time)
type_event = db.Column(db.String)
time_create = db.Column(db.DateTime)
wait_size_users = db.Column(db.Integer)
employer_id = db.Column(db.Integer, db.ForeignKey('employer.id'))
connect_employer = db.relationship('Employer', backref='advertisement_employer')
......@@ -174,13 +168,21 @@ class CommunityAdv(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
community_id = db.Column(db.Integer, db.ForeignKey('community.id'))
connect_community_id = db.relationship('Community', backref='advertisement_community')
connect_community_id = db.relationship('Community', backref='comm_adv_comm_id_community')
adv_id = db.Column(db.Integer, db.ForeignKey('advertisement.id'))
connect_adv_id = db.relationship('Advertisement', backref='advertisement_community')
connect_adv_id = db.relationship('Advertisement', backref='comm_adv_adv_id_advertisements')
def __init__(self):
pass
is_repost = db.Column(db.Boolean)
reposted_by = db.Column(db.Integer, db.ForeignKey('customers.id'))
connect_reposted_by = db.relationship('Customers', backref='comm_adv_reposted_by_customers')
def __init__(self, new_community_id, new_adv_id, new_is_repost, new_reposted_by):
self.community_id = new_community_id
self.adv_id = new_adv_id
self.is_repost = new_is_repost
self.reposted_by = new_reposted_by
class TagsCategories(db.Model):
......@@ -194,6 +196,21 @@ class TagsCategories(db.Model):
connect_tags = db.relationship('Tags', backref='cat_tags')
class TagsCommunity(db.Model):
__tablename__ = 'tags_community'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
tags_id = db.Column(db.Integer, db.ForeignKey('tags.id'))
connect_tags = db.relationship('Tags', backref='tags_community')
community_id = db.Column(db.Integer, db.ForeignKey('community.id'))
connect_community = db.relationship('Community', backref='tags_community_community')
def __init__(self, new_tag_name, new_community_id):
self.tag_name = new_tag_name
self.community_id = new_community_id
class TagsAdvertisement(db.Model):
"""Вспомагаткльная таблица для связи Событий и тегов"""
__tablename__ = 'tags_advertisement'
......@@ -236,5 +253,6 @@ class ClickHistory(db.Model):
tags_id = db.Column(db.Integer, db.ForeignKey('tags.id'))
connect_tags = db.relationship('Tags', backref='tags_clicks')
def __init__(self):
pass
\ No newline at end of file
def __init__(self, user_id, tags_id):
self.user_id = user_id
self.tags_id = tags_id
......@@ -37,6 +37,7 @@ admin.add_view(AdvertisementView(Advertisement, db.session))
admin.add_view(ModelView(ApprovedCustomer, db.session))
admin.add_view(ModelView(CommunityAdv, db.session))
admin.add_view(ModelView(ClickHistory, db.session))
admin.add_view(ModelView(TagsCommunity, db.session))
admin.add_view(ModelView(TagsCategories, db.session))
admin.add_view(ModelView(TagsUsers, db.session))
......
from web_setting import flask_app, cross_origin
from api.api_advertisment import all_advertisments
from api.api_advertisment import all_advertisments, indexes_advertisments, filter_advertisments
from api.api_customers import filter_customers
from pydantic import BaseModel, constr
from typing import Optional
from flask import jsonify, request
from routers.all_dataclasses import TagsIndex, FilterRad
from buisness_logic.insert_models import add_new_click
from recomendation_system import get_recomendation_by_tags, get_recomendation_by_location
@flask_app.route('/api/advertisement', methods=["POST", "GET"])
def advertisement():
if request.method == 'GET':
return jsonify(all_advertisments())
if request.method == 'POST':
return jsonify('XER')
@flask_app.route('/api/advertisement/get/<int:adv_id>_<int:user_id>/', methods=["GET"])
def get_advertisement(adv_id=None, user_id=None):
if adv_id is not None:
js_result = filter_advertisments(id_adv=adv_id)
for _ in js_result:
tag_id = []
for val in _['adv_id_tagsadv']:
tag_id.append(val['connect_tags']['id'])
con_tags = TagsIndex(tags_id=tag_id, index_connect=user_id)
add_new_click(con_tags)
return jsonify(js_result)
return jsonify('Error'), 401
@flask_app.route('/api/advertisement/recomendate/<int:user_id>/', methods=["GET"])
def recomendate_advertisement(user_id=None):
if user_id is not None:
advertisments_ids = get_recomendation_by_tags(user_id)
return indexes_advertisments(advertisments_ids)
return jsonify('Error'), 401
@flask_app.route('/api/advertisement/filter/rad/', methods=["POST"])
def routers_advertisement():
if request.method == 'POST':
data_user = FilterRad(**request.get_json())
if data_user.coordinate is None:
data_user.coordinate = filter_customers(user_id=data_user.user_id)[0]['coordinates']
try:
id_adv = []#вызов функции(FilterRad.coordinate, FilterRad.rad)
except:
jsonify('XER'), 401
indexes_advertisments(id_adv)
return jsonify('XER')
from pydantic import BaseModel, constr
from typing import Optional
from typing import Optional, List
class EntryDate(BaseModel):
"""Описание JSON ввиде модели, что-то вроде датаклассов,
Эти поля Федя отправляет с фронта"""
user_name: Optional[str] = None
login: constr(min_length=2, max_length=20)
password: constr(min_length=7, max_length=100)
role: Optional[int] = None
email: Optional[str] = None
coordinat: Optional[str] = None
description: Optional[str] = None
class TagsIndex(BaseModel):
index_connect: int
tags_id: List[int]
tags_name: Optional[str] = None
class FilterRad(BaseModel):
user_id: int
rad: float
coordinate: Optional[str] = None
class AdvertisementData(BaseModel):
-
\ No newline at end of file
pass
\ No newline at end of file
......@@ -2,20 +2,9 @@ from web_setting import flask_app, cross_origin
from api.api_auth import login
from buisness_logic.insert_models import add_new_users
from pydantic import BaseModel, constr
from typing import Optional
from flask import jsonify, request
from routers.all_dataclasses import EntryDate
class EntryDate(BaseModel):
"""Описание JSON ввиде модели, что-то вроде датаклассов,
Эти поля Федя отправляет с фронта"""
user_name: Optional[str] = None
login: constr(min_length=2, max_length=20)
password: constr(min_length=7, max_length=100)
role: Optional[str] = None
email: Optional[str] = None
from flask import jsonify, request
@flask_app.route('/register', methods=['POST'])
......@@ -30,7 +19,7 @@ def register_user():
def login_user():
"""Возвращает JWT токен"""
login_data = EntryDate(**request.get_json())
return jsonify(access_token=login(login_data))
return jsonify(login(login_data))
......
from web_setting import flask_app, cross_origin
from api.api_users import all_users
from api.api_advertisment import all_advertisments
from api.api_customers import all_customers, filter_customers
from buisness_logic.insert_models import add_new_users
......@@ -15,7 +15,20 @@ def users():
return jsonify(result)
@flask_app.route('/api/advertisment', methods=["GET"])
def tags():
result = all_advertisments()
@flask_app.route('/api/cust', methods=["GET"])
def customers():
result = all_customers()
return jsonify(result)
@flask_app.route('/api/cust/filter/login/<string:login>/', methods=["GET"])
@flask_app.route('/api/cust/filter/user_id/<int:user_id>/', methods=["GET"])
def cust_filter(login=None, user_id=None):
result = filter_customers(login=login, user_id=[user_id])
return jsonify(result)
@flask_app.route('/api/customers/filter/tags/', methods=["POST"])
def cust_filter_tag():
result = filter_customers(tags=request.json.get('tags', None))
return jsonify(result)
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment