Exemplo n.º 1
0
def edit_news(id):
    form = JobsForm()
    if request.method == "GET":
        db_sess = db_session.create_session()
        jobs = db_sess.query(Jobs).filter(Jobs.id == id | Jobs.id == 1).first()
        if jobs:
            jobs.job = form.job.data
            jobs.team_leader = form.team_leader.data
            jobs.duration = form.duration.data
            jobs.collaborators = form.collaborators.data
            jobs.is_finished = form.is_finished.data
        else:
            abort(404)
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        jobs = db_sess.query(Jobs).filter(Jobs.id == id | Jobs.id == 1).first()
        if jobs:
            jobs.job = form.job.data
            jobs.team_leader = form.team_leader.data
            jobs.duration = form.duration.data
            jobs.collaborators = form.collaborators.data
            jobs.is_finished = form.is_finished.data
            return redirect('/')
        else:
            abort(404)
    return render_template('jobs.html',
                           title='Redactioning of work',
                           form=form)
Exemplo n.º 2
0
def vote():
    if not fl.current_user.is_authenticated:
        return json.dumps({
            "status":
            "error",
            "message":
            "Чтобы голосовать, вы должны быть авторизованы"
        })
    if "value" not in request.form.keys() or \
            "uid" not in request.form.keys() or \
            "type" not in request.form.keys():
        return json.dumps({"status": "error", "message": "Неверный запрос"})
    try:
        uid = int(request.form['uid'])
    except Exception:
        return json.dumps({"status": "error", "message": "Неверный запрос"})
    value = 1 if request.form['value'] == "plus" else -1
    if request.form['type'] == "vote_user":
        status = DataBaseWorker.vote_user(dbs.create_session(), uid, value)
    else:
        status = DataBaseWorker.vote_post(dbs.create_session(), uid, value)
    if status != "error":
        return json.dumps({"status": "ok", "value": status})
    else:
        return json.dumps({
            "status": "error",
            "message": "Не удалось проголосовать"
        })
Exemplo n.º 3
0
def new_job():
    form = NewJobForm()
    if form.validate_on_submit():
        resp = check_job(form, 'newjob.html')
        if resp['response'][0] != 'OK':
            return render_template(resp['response'][0],
                                   add_title='New job',
                                   title='New job',
                                   form=resp['response'][1])
        sesion = db_session.create_session()
        category_id = form.category_id.data
        check_cat_exists(category_id)
        sesion = db_session.create_session()
        categ = sesion.query(Category).filter(
            Category.cat_id == category_id).first()
        print(categ)
        job = Jobs(team_leader=form.team_leader.data,
                   job=form.job.data,
                   work_size=form.work_size.data,
                   collaborators=form.collaborator.data,
                   start_date=resp['response'][1],
                   end_date=resp['response'][2],
                   is_finished=form.is_finished.data,
                   creator_id=current_user.id)
        job.categories.append(categ)
        sesion.add(job)
        sesion.commit()
        sesion.close()
        return redirect('/')
    return render_template('newjob.html',
                           add_title='New job',
                           title='New job',
                           form=form)
Exemplo n.º 4
0
def editPages(category_id, story_id):
    # start an sql session
    session = create_session()
    # get category
    category = session.query(Category).get(category_id)
    # get story
    story = session.query(Story).get(story_id)
    # get list of pages
    pages = session.query(Story_Page).filter_by(story_id=story.id).all()
    # close session
    session.close()
    if len(pages) == 0:
        # redirect
        return redirect(
            url_for("addStoryPage",
                    category_id=category_id,
                    story_id=story_id,
                    linking_page_id=0))
    else:
        # get root page
        session = create_session()
        root_page = session.query(Story_Page).filter_by(story_id=story.id,
                                                        is_root=True).one()
        session.close()
        # create page tree
        page_tree = [create_page_tree(root_page, None, 0)]
        user = get_user()
        return render_template("editPages.html",
                               story=story,
                               category=category,
                               page_tree=page_tree,
                               user=user)
def analyze_description(pr_id, is_editing=False):
    '''Функция, которая анализирует краткое описание на ключевые слова и добавляет их в бд'''
    #Подключаемся к бд, достаем проект и анализируем его краткое содержание
    global_init("db.sqlite")
    project_id = pr_id
    sesion = create_session()
    project = sesion.query(Projects).get(project_id)  # type: Projects
    if is_editing:
        sesion = create_session()
        tags = sesion.query(project_tag_table).get(project.id).all()
        if tags:
            deliting_elements = project_tag_table.delete().where(
                Projects.id == project.id)
            sesion.execute(deliting_elements)
            sesion.commit()
    probable_tags = []
    all_tags = set()
    #Анализ - проход по всем словам и проверка есть ли оне в файле с тегами или начинаются ли они на ~
    #Если есть или начинаются - добавить их к тегам проекта
    with open(os.path.join(os.getcwd(),
                           'data/main_tags.txt')) as main_tags_file:
        for word in main_tags_file.readlines():
            all_tags.add(word.strip())
    formatted_words = project.filter_text()
    for word in formatted_words:
        word = word.strip()
        if (word.startswith('~') and word[1:] in all_tags) or word in all_tags:
            probable_tags.append(word.replace('~', ''))
        elif word.startswith('~'):
            probable_tags.append(word[1:])
    return probable_tags
Exemplo n.º 6
0
def del_subject(subject): 
    session = db_session.create_session()
    s = session.query(Subject).filter(Subject.id == subject.id).first()
    session.delete(s)
    session.commit()
    session = db_session.create_session()
    check = session.query(Subject).filter(Subject.id == subject.id).first()
    if not check:
        return True
    else:
        return False
Exemplo n.º 7
0
def del_course(course_id):
    session = db_session.create_session()
    c = session.query(Course).filter(Course.id == course_id).first()
    s_id = c.subject_id
    session.delete(c)
    session.commit()
    session = db_session.create_session()
    check = session.query(Course).filter(Course.id == course_id).first()
    if not check:
        return s_id
    else:
        return False
Exemplo n.º 8
0
def topic_add():
    if not fl.current_user.is_authenticated:
        return perm_error(
            error="Чтобы добавить тему, вы должны быть авторизованы.")
    if fl.current_user.is_banned():
        return perm_error(error="Ваш аккаунт заблокирован.")
    controller = TopicAddController()
    if "category" in request.args.keys():
        return controller.view(dbs.create_session(),
                               category=request.args['category'])
    else:
        return controller.view(dbs.create_session())
Exemplo n.º 9
0
def base():
    sesion = db_session.create_session()
    if request.args.get('type', 'job') == 'dep':
        print()
        deprts = {'deps': []}
        for dep in sesion.query(Departments):
            dep_json = {'dep': {}}
            dep_json['dep']['user'] = dep.chief_m
            dep_json['dep']['dep'] = dep
            if current_user.is_authenticated and current_user.id == dep.chief_m.id:
                dep_json['dep']['btns'] = True
            deprts['deps'].append(dep_json)
        return render_template('jobs.html',
                               type='dep',
                               deprts=deprts,
                               ad_tit='Departments')
    else:
        jobs = {'jobs': []}
        for job in sesion.query(Jobs):
            job_json = {'job': {}}
            job_json['job']['user'] = job.tm_leader
            job_json['job']['job'] = job
            if current_user.is_authenticated and (
                    current_user.id == job.tm_leader.id
                    or current_user.id == job.creator_id):
                job_json['job']['btns'] = True
            jobs['jobs'].append(job_json)
        return render_template('jobs.html',
                               jobs=jobs,
                               type='job',
                               ad_tit='Jobs')
def choose_project():
    sesion = create_session()
    if current_user.is_anonymous:
        last_prjct_id = request.cookies.get('last_project_id', None)
        if last_prjct_id:
            last_prjct_id = int(last_prjct_id) + 1
        else:
            last_prjct_id = 1
    else:
        last_prjct_id = request.cookies.get('last_project_id', None)
        if last_prjct_id:
            last_prjct_id = int(last_prjct_id) + 1
        else:
            last_prjct_id = 1
        project = sesion.query(Projects).get(last_prjct_id)
        try:
            max_id = sesion.query(func.max(Projects.id))[0][0]
        except:
            max_id = 2
        s = select([ranked_table
                    ]).where(ranked_table.c.user_id == current_user.id)
        conn = create_coon()
        ranked_projects = [row[1] for row in conn.execute(s)]
        while (not project
               or project.id in ranked_projects) and last_prjct_id <= max_id:
            last_prjct_id += 1
            project = sesion.query(Projects).get(last_prjct_id)
    if not project:
        return None
    return (project, last_prjct_id)
Exemplo n.º 11
0
def get_products():
    db_sess = db_session.create_session()
    news = db_sess.query(Items).all()
    return jsonify({
        "products":
        [item.to_dict(only=('title', 'price', 'rest')) for item in news]
    })
Exemplo n.º 12
0
 def delete(self, good_id):
     abort_if_good_not_found(good_id)
     session = db_session.create_session()
     good = session.query(Good).get(good_id)
     session.delete(good)
     session.commit()
     return jsonify({'success': 'OK'})
Exemplo n.º 13
0
def register_project():
    print(current_user.id)
    form = RegisterProjectForm()
    if request.method == 'POST' and form.validate_on_submit():
        project = Projects(name=form.name.data,
                           short_description=form.short_description.data,
                           full_description=form.full_description.data,
                           owner_id=current_user.id)
        resp = check_project(form)
        # checking is all data in form is good
        if resp != 'OK':
            err_attr = getattr(form, resp[0])
            err_attr.errors.append(resp[1])
            return render_template('register_project.html',
                                   form=form,
                                   title='Register project')
        sesion = db_session.create_session()
        # getting this project id
        last_id = sesion.query(func.max(Projects.id)).one()

        # saving image for this project
        image = request.files.get('image_field')
        if not last_id[0]:
            last_id = 1
        else:
            last_id = int(last_id[0]) + 1
        if image and image.filename.rsplit('.')[1] in ['png', 'jpg', 'jpeg']:
            filename = f'{current_user.id}_{last_id}.jpg'
            global_file_path = os.path.join(
                app.config['UPLOAD_FOLDER'],
                os.path.join('project_imgs', filename))
            image.save(global_file_path)
            project.image_path = url_for(
                'static', filename=f'imgs/project_imgs/{filename}')
        else:
            project.image_path = url_for(
                'static', filename='imgs/project_imgs/no_project_image.jpg')
        for username in form.collaborators.data.split(', '):
            user = sesion.query(User).filter(
                User.username == username.strip()[1:]).first()
            if user:
                project.collaborators.append(user)
        sesion.add(project)
        sesion.commit()
        sesion.close()
        print('subprocess with last_id:', last_id)

        probable_tags = analyze_description(last_id)
        # subprocess.call(f'python analyze_description.py {last_id}', shell=True)
        if len(probable_tags) > 0:
            response = make_response(
                redirect(
                    url_for('blog.check_tags',
                            id=str(last_id),
                            tags=','.join(probable_tags))))
            return response
        return redirect(url_for('base'))
    return render_template('register_project.html',
                           form=form,
                           title='Register project')
def showPageJSON(category_id, story_id, page_id):
    # start sql session
    session = create_session()
    # get category
    category = session.query(Story).get(category_id)
    if not category:
        return None
    # get story
    story = session.query(Story).get(story_id)
    if not story:
        return None
    # get root page if a page is not specified
    page = None
    if page_id == 0:
        page_query = session.query(Story_Page).filter_by(is_root=True,
                                                         story_id=story.id)
        if page_query.count() > 0:
            page = page_query.one()
    # page was specified
    else:
        page = session.query(Story_Page).get(page_id)
    # get linked pages
    linked_pages = []
    if page:
        linked_pages = session.query(Story_Page).     \
            filter(Story_Page.id==Page_Link.linked_page_id). \
            filter(Page_Link.base_page_id==page.id).         \
            all()
    # close sql session
    session.close()
    # get json
    return jsonify(Page=page.serialize,
                   Linked_Pages=[lp.serialize for lp in linked_pages],
                   Story=story.serialize,
                   Category=category.serialize)
Exemplo n.º 15
0
def get_user(user_id):
    sesion = db_session.create_session()
    user = sesion.query(User).get(user_id)
    if not user:
        return jsonify({'error': 'user not found'})
    sesion.close()
    return jsonify({'user': user.to_dict(rules=('-id', '-hashed_password'))})
Exemplo n.º 16
0
def newStory():
    user = get_user()
    # start sql session
    session = create_session()
    # get categories
    categories = session.query(Category).all()
    # Protect this page by login
    if user == None:
        return redirect(url_for("login"))
    # if submitted form
    if request.method == 'POST':
        # get category that the story is being posted to
        category_id = request.form['category']
        # create new story
        story = Story(name=request.form['name'],
                      description=request.form['description'],
                      category_id=category_id,
                      owner_id=user.id)
        session.add(story)
        # close sql session
        session.commit()
        session.close()
        return redirect(url_for('showCategory', category_id=category_id))
    else:
        # close sql session
        session.close()
        return render_template("newStory.html",
                               categories=categories,
                               user=user)
Exemplo n.º 17
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        sesion = db_session.create_session()
        if sesion.query(User).filter(User.email == form.email.data).first():
            form.email.errors.append('Email already exists')
            return render_template('register.html',
                                   form=form,
                                   title='Register')
        elif sesion.query(User).filter(
                User.username == form.login.data).first():
            form.login.errors.append('Username already exists')
            return render_template('register.html',
                                   form=form,
                                   title='Register')
        new_user = User(surname=form.surname.data,
                        name=form.name.data,
                        email=form.email.data,
                        age=form.age.data,
                        position=form.position.data,
                        speciality=form.speciality.data,
                        address=form.address.data,
                        username=form.login.data)
        new_user.set_password(form.password.data)
        sesion.add(new_user)
        sesion.commit()
        return redirect('/')
    return render_template('register.html', form=form, title='Register')
Exemplo n.º 18
0
def register():
    form = RegisterUserForm()
    # вывод списка стран
    countries_list = [
        (country, country) for country in
        [line.strip() for line in open('data/countries.txt').readlines()]
    ]
    form.country.choices = countries_list
    if request.method == 'POST' and form.validate_on_submit():
        ans = check_new_user(form)
        if ans != 'OK':
            attr = getattr(form, ans[0])
            attr.errors.append(ans[1])
            return render_template('register.html',
                                   form=form,
                                   title='Register')
        user = User(name=form.name.data,
                    surname=form.surname.data,
                    username=form.username.data,
                    email=form.email.data,
                    description=form.description.data,
                    country=form.country.data,
                    age=form.age.data,
                    register_date=datetime.datetime.now())
        user.set_password(form.password.data)
        sesion = db_session.create_session()
        sesion.add(user)
        sesion.commit()
        sesion.close()
        return redirect(url_for('authen.login'))
    return render_template('register.html', form=form, title='Register')
Exemplo n.º 19
0
def get_chat_messages(chat: Union[int, Chat], sort_param: Optional[InstrumentedAttribute] = None,
                      session: Optional[Session] = None) -> List[Message]:
    if session is None:
        session = create_session()
    if isinstance(chat, Chat):
        chat = chat.id
    return session.query(Message).filter(Message.chat_id == chat).order_by(sort_param).all()
Exemplo n.º 20
0
def get_chat_by_id(chat_id: int, session: Optional[Session] = None) -> Chat:
    if session is None:
        session = create_session()
    chat = session.query(Chat).filter(Chat.id == chat_id).first()
    if chat is None:
        raise NotFoundError(f"Chat with id {chat_id} not found")
    return chat
Exemplo n.º 21
0
def set_user_perm(user_id: int):
    if not fl.current_user.is_admin():
        return "Error. You are not admin!"
    try:
        if "status" not in request.args.keys():
            return "Error. Status argument not found"
        session = dbs.create_session()
        user = session.query(User).get(user_id)
        if not user:
            return "Error. User not found"
        status = request.args['status']
        if status == "block":
            user.status = 3
            session.add(user)
            session.commit()
        elif status == "user":
            user.status = 1
            session.add(user)
            session.commit()
        elif status == "admin":
            user.status = 2
            session.add(user)
            session.commit()
        return redirect("/admin")
    except Exception as ex:
        return "Fatal error. " + str(ex)
def deleteStory(category_id, story_id):
    # start sql session
    session = create_session()
    # get category
    category = session.query(Category).get(category_id)
    cat_id = category.id
    # get story
    story = session.query(Story).get(story_id)
    if request.method == 'POST':
        # delete all page links associated with story
        session.query(Page_Link).filter_by(story_id=story.id).delete()
        # delete all pages associated with story
        session.query(Story_Page).filter_by(story_id=story.id).delete()
        # delete story
        session.query(Story).filter_by(id=story.id).delete()

        # close session and redirect
        session.commit()
        session.close()
        return redirect(url_for('showCategory', category_id=category_id))
    else:
        # close session
        session.close()
        user = get_user()
        return render_template("deleteStory.html",
                               story=story,
                               category=category,
                               user=user)
def editStoryPage(category_id, story_id, page_id):
    # start an sql session
    session = create_session()
    # get category
    category = session.query(Category).get(category_id)
    # get story
    story = session.query(Story).get(story_id)
    # get page
    page = session.query(Story_Page).get(page_id)
    # post
    if request.method == 'POST':
        # edit the page
        page.name = request.form['name']
        page.description = request.form['description']
        page.text = request.form['text']
        # add and commit
        session.add(page)
        session.commit()
        # close session
        session.close()
        return redirect(
            url_for("editPages", category_id=category_id, story_id=story_id))
    else:
        session.close()
        user = get_user()
        return render_template("editStoryPage.html",
                               category=category,
                               story=story,
                               page=page,
                               user=user)
Exemplo n.º 24
0
def api_user_get():
    def error(msg: str):
        return jsonify({"status": "error", "message": msg})

    if "api_key" not in request.args:
        return error("invalid api key")
    session = create_session()
    user = api_key_check(request.args['api_key'], session)
    if not user:
        return error("invalid api key")
    if "nickname" not in request.args:
        return error("nickname not specified")
    f_user = session.query(User).filter(
        User.nickname == request.args['nickname']).first()
    if not f_user:
        return error("user not found")
    return jsonify({
        "status": "ok",
        "user": {
            "id": f_user.id,
            "sex": f_user.sex,
            "email": f_user.email,
            "nickname": f_user.nickname,
            "register_date": f_user.reg_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
            "avatar": request.url_root + "uploads/profiles/" + f_user.avatar,
            "rating": f_user.rating
        }
    })
Exemplo n.º 25
0
def buy_item(telegram_id, table_name, item, count):
    try:
        session = create_session()

        if "bee" in item and "hive" not in item:
            beehives = session.query(Beehives).filter(
                Beehives.telegram_id == telegram_id).one()
            all_beehives = beehives.small_beehives + beehives.medium_beehives + beehives.large_beehives
            bee_count = sum(get_bees(telegram_id))
            if all_beehives < bee_count / 100 + 1:
                return 'Not enough storage'

        cash = session.query(User).filter(
            User.telegram_id == telegram_id).one().balance

        price = constants.ITEM_PRICES[item] * count

        if price > cash:
            return "Not enough cash"

        table = table_names[table_name]
        session.query(table).filter(table.telegram_id == telegram_id).update(
            {getattr(table, item): getattr(table, item) + count})
        session.query(User).filter(User.telegram_id == telegram_id).update(
            {User.balance: cash - price})

        session.commit()
        return "200"
    finally:
        session.close()
Exemplo n.º 26
0
def find():
    if request.method == 'GET':
        return render_template("find.html",
                               pos=0,
                               ot="Россия",
                               ku="Без разницы",
                               d1="",
                               d2="",
                               dat1=datetime.date.today(),
                               dat2=datetime.date.today() +
                               datetime.timedelta(days=365),
                               lev="Любой",
                               pit="Любой",
                               st1="",
                               st2="")

    elif request.method == 'POST':
        otkuda = request.form['otkuda']
        kuda = request.form['kuda']
        dni1 = request.form['dni1']
        if dni1 == "":
            dni1 = 1
        dni2 = request.form['dni2']
        if dni2 == "":
            dni2 = 21
        data1 = request.form['data1']
        data_d1 = datetime.date(int(data1[0:4]), int(data1[5:7]),
                                int(data1[8:10]))
        data2 = request.form['data2']
        data_d2 = datetime.date(int(data2[0:4]), int(data2[5:7]),
                                int(data2[8:10]))
        level = request.form['level']
        pitanie = request.form['pitanie']
        cena1 = request.form['cena1']
        if cena1 == "":
            cena1 = 0
        cena2 = request.form['cena2']
        if cena2 == "":
            cena2 = 200000

        db_session.global_init("db/database.sqlite")
        session = db_session.create_session()
        name = session.query(tyrs.Tyrs).filter(tyrs.Tyrs.Otkuda==otkuda).filter((tyrs.Tyrs.Kuda==kuda) | (kuda=="Без разницы")).\
            filter(data_d1<=tyrs.Tyrs.Data).filter(tyrs.Tyrs.Data<=data_d2).\
            filter(int(dni1)<=tyrs.Tyrs.Dni).filter(tyrs.Tyrs.Dni<=int(dni2)).filter((tyrs.Tyrs.Level==level) | (level=="Любой")).\
            filter((tyrs.Tyrs.Pitanie==pitanie) | (pitanie=="Любой")).filter(int(cena1)<=tyrs.Tyrs.Cena).filter(tyrs.Tyrs.Cena<=int(cena2))
        session.commit()
        return render_template("find.html",
                               pos=1,
                               tyrs=name,
                               ot=otkuda,
                               ku=kuda,
                               d1=dni1,
                               d2=dni2,
                               dat1=data1,
                               dat2=data2,
                               lev=level,
                               pit=pitanie,
                               st1=cena1,
                               st2=cena2)
Exemplo n.º 27
0
def reqister():
    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   title='Register Form',
                                   form=form,
                                   message="Пароли не совпадают")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Register Form',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(surname=form.surname.data,
                    name=form.name.data,
                    email=form.email.data,
                    position=form.position.data,
                    speciality=form.speciality.data,
                    address=form.address.data,
                    age=form.age.data)
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    return render_template('register.html', title='Register form', form=form)
Exemplo n.º 28
0
def get_jobs():
    sesion = db_session.create_session()
    jobs = sesion.query(Jobs).all()
    return jsonify({
        'response': 200,
        'jobs': [job_to_dict(job) for job in jobs]
    })
Exemplo n.º 29
0
 def __init__(self):
     self.view_includes.clear()
     self.view_includes["css"] = ""
     self.css("main.css")
     self.view_includes["js"] = ""
     self.javascript("jquery.js", "main.js")
     self.db_session = create_session()
Exemplo n.º 30
0
def add_job():
    if not request.json:
        return jsonify({'error': 'Emty request'})
    req_keys = [
        el.name for el in Jobs.__table__.columns
        if el.name not in ['id', 'end_date', 'start_date']
    ]
    if not all([key in request.json for key in req_keys]):
        return jsonify({'error': 'Bad json'})
    sesion = db_session.create_session()
    if not sesion.query(User).filter(
            User.id == request.json['creator_id']).first():
        return jsonify({'error': 'creator not found'})
    if not sesion.query(User).filter(
            User.id == request.json['team_leader']).first():
        return jsonify({'error': 'team leader not found'})
    if not isinstance(request.json['work_size'],
                      float) or request.json['work_size'] <= 0:
        return jsonify({'error': 'bad work size'})

    job = Jobs(collaborators=request.json['collaborators'],
               creator_id=int(request.json['creator_id']),
               is_finished=request.json['is_finished'],
               work_size=request.json['work_size'],
               team_leader=request.json['team_leader'],
               job=request.json['job'],
               start_date=datetime.fromisoformat(request.json['start_date']))
    sesion.add(job)
    sesion.commit()
    sesion.close()
    return jsonify({'succes': 'OK'})