Example #1
0
def get_new_post():
    """
    Add new post into the database.

    VK CALLBACK API send a json for completed event in group.
    event = new post EXCEPT A SUGGESTED POSTS
    """

    response = request.json
    obj = response['object']
    if obj['post_type'] != 'post':
        return

    session = get_db_session()

    # if post is already in the db --> exit
    if session.query(Post).filter(Post.vk_id == int(obj['id'])).first():
        return
    if 'attachments' not in obj.keys() or \
            sum(map(lambda att: 1 if att['type'] == 'photo' else 0, obj['attachments'])) > 1 \
            or 'photo' not in obj['attachments'][0].keys():
        return

    # create the Post obj. and add it into the db
    post = Post(vk_id=obj['id'],
                photo_url=obj['attachments'][0]['photo']['photo_807']
                if 'photo_807' in obj['attachments'][0]['photo'].keys() else
                obj['attachments'][0]['photo']['photo_604'])
    session.add(post)
    session.commit()
Example #2
0
    def get(self):
        """
        :return: object with list of fav posts
        """

        user_id = current_user.id
        session = get_db_session()
        user = session.query(User).filter(User.id == user_id).first()
        posts = user.favors
        return jsonify({'posts': [post.to_dict(only=('id', 'vk_id', 'photo_url'))
                                  for post in posts[::-1]]})
Example #3
0
def check_login(nickname):
    """
    :param nickname: user's entered nickname

    :return: response 404 if user doesn't exist else obj with message about user's existing
    """

    session = get_db_session()
    user = session.query(User).filter(User.nickname == nickname).first()
    return jsonify({'response': 'user has found'}) if user \
        else make_response(jsonify({"error": "user doesn't exist"}), 404)
Example #4
0
def check_id(vk_id):
    """
    :param vk_id: user's vk id for checking

    :return: response 404 if account doesn't register
             else obj with message about account's registration
    """

    session = get_db_session()
    user = session.query(User).filter(User.vk_domain == vk_id).first()
    return jsonify({'response': 'current account has already register'}) if user \
        else make_response(jsonify({"error": "account with this id doesn't exist"}), 404)
Example #5
0
    def delete(self):
        """
        Getting obj with group id from the request;
        Getting current user's id;

        Delete from favorites table association user-post with.
        """

        post_id = parser.parse_args()['post_id']
        user_id = current_user.id
        session = get_db_session()
        user = session.query(User).filter(User.id == user_id).first()
        post = session.query(Post).filter(Post.id == post_id).first()
        user.favors.remove(post)
        session.commit()
Example #6
0
def login():
    args = request.args
    if args:
        db_session = get_db_session()
        user = db_session.query(User).filter(
            User.vk_domain == args.get('uid')).first()
        if not user:
            return render_template(
                'login.html',
                title='Вход',
                message="Такой пользователь не зарегистрирован",
                **VK_PARAMS)
        login_user(user)
        return redirect("/")
    return render_template('login.html', title='Вход', **VK_PARAMS)
Example #7
0
def the_new_newly_created_entry_with_payload_exists_on_the_database(
        context, payload):
    """the new newly created entry with <payload> exists on the database."""
    if context["response"].status_code == 201:
        payload = json.loads(payload)
        row_id = json.loads(context["response"].data)["id"]
        db = get_db_session(context["username"])
        instance = FRDMmoAccFactory.get_by_id(db, row_id)
        assert instance.id.value == row_id
        assert all(payload[key] == getattr(instance, key).value
                   for key in payload)
        assert instance.created_by.value == context["username"]
        assert instance.created_date is not None
        assert instance.last_updated_by.value == context["username"]
        assert instance.last_update_date.value == instance.created_date.value
    else:
        print(f"Skipping checking payload because response was not 2XX")
Example #8
0
def get_posts():
    """
    :return: obj with list of posts

    Type of posts is selected based on the type of page, from which the request was received.
    """

    session = get_db_session()
    post_type = request.args.get('type')

    posts = []
    if post_type == 'all':
        posts = session.query(Post).all()
    elif post_type == 'fav':
        posts = session.query(User).filter(User.id == current_user.id).first().favors
    elif post_type == 'sug':
        return jsonify({'posts': get_suggests(current_user.access_token)})
    return jsonify({'posts': [post.to_dict(only=('id', 'vk_id', 'photo_url'))
                              for post in posts[::-1]]})
Example #9
0
    def post(self):
        """
        Getting from the request obj with registration info:
        nickname, access token, vk id

        Create User obj and add it into the db.
        """

        arg = parser.parse_args()
        session = get_db_session()
        if session.query(User).filter(
                User.vk_domain == arg['vkDomain']).first():
            return make_response(
                jsonify({'error': 'this VK account has already registered'}),
                400)
        user = User(nickname=arg['nickname'],
                    vk_domain=arg['vkDomain'],
                    access_token=arg['accessToken'],
                    is_admin=is_admin(arg['vkDomain'], arg['accessToken'],
                                      int(app.config['VK_GROUP_ID'][1:])))
        session.add(user)
        session.commit()
        return jsonify({'success': 'OK'})
Example #10
0
 def setUp(self) -> None:
     self.test_model = ExampleFactory("test_str1", "test_str2")
     self.test_real_model = FRDMmoAccFactory()
     self.db = get_db_session(DB_USERNAME)
Example #11
0
def load_user(user_id):
    db_session = get_db_session()
    return db_session.query(User).get(user_id)
Example #12
0
from flask import render_template, redirect, request
from flask_login import login_required, logout_user, login_user

from app import app, get_db_session, login_manager
from app.models import User
from app.forms import RegisterForm, PostForm

import logging

from loading_posts import load_posts

# loading all posts from the group wall
load_posts(app.config['ACCESS_TOKEN'], app.config['VK_GROUP_ID'],
           get_db_session())

logging.getLogger('serializer').setLevel(logging.WARNING)
logging.basicConfig(level=logging.INFO)

# static params for pages templates
VK_PARAMS = {
    'group_id': app.config['VK_GROUP_ID'],
    'client_id': app.config['CLIENT_ID'],
    'screen_name': app.config['VK_SCREEN_NAME'],
    'group_name': app.config['VK_GROUP_NAME']
}


@app.errorhandler(404)
def page_not_found(error):
    return render_template('error.html', error=error, **VK_PARAMS), 404