Exemple #1
0
def api_get_like(uid, pid, aid):
    """
    Determines the like-glyph value for the given triplet

    :param uid:     Flickipedia user id
    :param pid:     Flickipedia photo id
    :param aid:     Flickipedia article id

    :return:    'Like' row if exists, None otherwise
    """

    # TODO - USE MODELS

    io = DataIOMySQL()
    io.connect()
    schema_obj = getattr(schema, 'Likes')

    # Query to extract
    res = io.session.query(schema_obj, schema_obj.is_set).filter(
        schema_obj.photo_id == pid,
        schema_obj.article_id == aid,
        schema_obj.user_id == uid
    ).limit(1).all()

    # Clean up connections
    io.sess.close()
    io.engine.dispose()

    if len(res) == 0:
        log.error('REST \'api_get_glyph\': Couldn\'t find ('
                  'user="******", photo_id=%s, article_id=%s)' % (
            uid, pid, aid))
        return None
    else:
        return res[0]
Exemple #2
0
def register_process():
    """
    Handles user registration
    """

    handle = escape(str(request.form['handle'].strip()))
    firstname = escape(str(request.form['fname'].strip()))
    lastname = escape(str(request.form['lname'].strip()))
    email = escape(str(request.form['email'].strip()))
    passwd = escape(str(request.form['passwd'].strip()))

    mysql_inst = DataIOMySQL()
    mysql_inst.connect()

    # TODO - check for duplicates / additional validation
    mysql_inst.insert(
        'User',
        handle=handle,
        email=email,
        firstname=firstname,
        lastname=lastname,
        password=hmac(passwd),
        date_join=int(time.time())
    )

    # TODO - error condition
    return render_template('login.html')
Exemple #3
0
class BaseModel(object):
    """
        Base class for model objects that can handle generic validation and state
        logic
    """

    def __init__(self):
        super(BaseModel, self).__init__()
        self.io = DataIOMySQL()
        self.io.connect()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.io.sess.close()
        self.io.engine.dispose()

    def alchemy_fetch_validate(self, sqlAlchemyQryObj, retType = RET_TYPE_ALLROWS):
        """
        Fault tolerance around query execution in sql alachemy
        :param schema_obj:
        :return:
        """
        retries = 0
        while retries < NUM_SQL_RETRIES:
            try:
                if retType == RET_TYPE_ALLROWS:
                    return sqlAlchemyQryObj.all()
                elif retType == RET_TYPE_COUNT:
                    return sqlAlchemyQryObj.count()
                elif retType == RET_TYPE_FIRSTROW:
                    return sqlAlchemyQryObj[0]
            except OperationalError:
                log.error('Failed to fetch article, trying again.')
                retries += 1
                time.sleep(0.5)
        return []
Exemple #4
0
def api_set_like(uid, pid, aid):
    """
    Toggles the like-glyph value for the given triplet

    :param uid:     Flickipedia user id
    :param pid:     Flickipedia photo id
    :param aid:     Flickipedia article id

    :return:    True on success, False otherwise
    """

    # TODO - USE MODELS

    io = DataIOMySQL()
    io.connect()

    result = api_get_like(uid, pid, aid)

    # toggle and set new value (delete row if it doesn't exist)
    if result:      # io.update false
        try:
            io.delete(result)
        except Exception as e:
            log.error(' "%s"' % e.message)
            return False

    else:           # io.update true
        try:
            io.insert('Like', user_id=uid, photo_id=pid, article_id=aid)
        except Exception as e:
            log.error(' "%s"' % e.message)
            return False

    # Clean up connections
    io.sess.close()
    io.engine.dispose()

    return True
Exemple #5
0
 def __init__(self):
     super(BaseModel, self).__init__()
     self.io = DataIOMySQL()
     self.io.connect()
Exemple #6
0
def main():

    # Parse cli args
    args = parseargs()

    io = DataIOMySQL()
    io.connect()

    if args.drop:
        io.drop_table('User')
        io.drop_table('Photo')
        io.drop_table('Article')
        io.drop_table('ArticleContent')
        io.drop_table('Like')
        io.drop_table('Exclude')
        io.drop_table('Upload')

    io.create_table('User')
    io.create_table('Photo')
    io.create_table('Article')
    io.create_table('ArticleContent')
    io.create_table('Like')
    io.create_table('Exclude')
    io.create_table('Upload')
Exemple #7
0
def mashup():

    DataIORedis().connect()
    mysql_inst = DataIOMySQL()
    mysql_inst.connect()

    # Check for POST otherwise GET
    refresh = False
    if request.form:
        article = str(request.form['article']).strip()
        article = '_'.join(article.split())
        log.debug('Processing POST - ' + article)

    else:
        article = str(request.args.get(settings.GET_VAR_ARTICLE)).strip()
        if 'refresh' in request.args:
            refresh = True
        article = '_'.join(article.split())
        log.debug('Processing GET - ' + article)

    # Fetch article count and stored body (if exists)
    article_count = get_article_count()
    body = get_article_stored_body(article)

    if not body or refresh:

        # Calls to Wiki & Flickr APIs
        try:
            wiki = call_wiki(article)
        except WikiAPICallError as e:
            return render_template(e.template, error=e.message)
        try:
            res_json = call_flickr(article)
        except FlickrAPICallError as e:
            return render_template(e.template, error=e.message)

        # Extract photo data
        photos = get_flickr_photos(res_json)
        if not photos:
            render_template('index.html', error="Couldn't find any photos "
                                                "for '{0}'!".format(article))

        # 1. Fetch the max article - Refresh periodically
        # 2. Remove a random article and replace, ensure that max has
        #       been fetched
        # 3. Article insertion and ORM fetch
        # 4. rank photos according to UGC
        # 5. Photo & markup parsing
        # 6. Article content insertion and ORM fetch
        max_aid = get_max_article_id()
        manage_article_storage(max_aid, article_count)
        article_id, insert_ok = handle_article_insert(article, wiki.pageid)
        photos = order_photos_by_rank(article_id, photos)
        page_content = prep_page_content(article_id, article, wiki, photos,
                                         User(current_user.get_id()))
        if insert_ok:
            handle_article_content_insert(article_id, page_content, not body)

    else:
        page_content = json.loads(body, object_hook=_decode_dict)
        # refresh the user id
        page_content['user_id'] = User(current_user.get_id()).get_id()

    # Update last_access
    with ArticleModel() as am:
        am.update_last_access(page_content['article_id'])

    log.info('Rendering article "%s"' % article)
    return render_template('mashup.html', **page_content)