Esempio n. 1
0
def create_post(user_id, lat, lon, body, artist, img_url="null"):
    p = Post(user_id, lat, lon, body, img_url)
    db_session.add(p)
    # make sure we update our database is updated with the id
    db_session.flush()
    db_session.commit()
    return {'success': 1, 'id': p.id, 'msg': 'success'}
Esempio n. 2
0
def comment():
    article_id = request.form.get('articleId') or 0

    if not article_id:
        return jsonify(state=False, message='文章不存在')

    user_id = session.get('userid')
    user_name = session.get('username')
    to_name = request.form.get('toName') or None
    content = request.form.get('content') or None

    if not content:
        return jsonify(state=False, message='评论内容不能为空')

    if not user_name or not user_id:
        return jsonify(state=False, message='用户未登录')

    user = db_session.query(User).filter(User.id == user_id).first()
    ## 向数据库添加一条评论
    c = Comment(article_id, user.id, user.name, user.head_url, to_name,
                content)
    db_session.add(c)
    db_session.flush()

    article_url = 'http://hamilton.duapp.com/detail?articleId=' + str(
        article_id)
    bmq.send_mail(['*****@*****.**'], 'hamilton上的新回复',
                  '<!--HTML-->\n您有一条新回复需要处理<br/>点击查看:<a href="' + article_url +
                  '">' + article_url + '</a>')

    return jsonify(state=True, message='success')
Esempio n. 3
0
def callback() :
  code = request.args.get('code', None)

  if code :
    token = social.get_access_token(code)
    access_token = token.get('access_token')

    if access_token :
      baidu_user = social.get_user_info(access_token)
      name = baidu_user.get('username')
      media_type = baidu_user.get('media_type')
      head_url = baidu_user.get('tinyurl')
      
      user = User.find_user(name, media_type)
      if not user and name :
        user = User(name, head_url = head_url, media_type = media_type)
        db_session.add(user)
        db_session.flush();

      if user :
        session['userid'] = user.id
        session['username'] = user.name
        session['is_admin'] = user.admin

  return redirect('/') 
Esempio n. 4
0
def edit_photo(photo_id):
    """ Updates a photo instance """
    photo = Photo.query.get(photo_id)
    if photo is None:
        return jsonify(errors="resource not found"), 404
    data = request.get_json()
    headers = request.headers
    jwt_token = headers['X-Authorization']
    message = {}
    # check for valid token
    try:
        decoded = jwt.decode(jwt_token, constants.SECRET_KEY)
    except jwt.exceptions.InvalidTokenError:
        message['error'] = 'token is invalid'
        return jsonify(message), 400
    # check to see if user owns photo
    if decoded['username'] != photo.user.username:
        return jsonify("You must own a photo to edit it"), 401
    if decoded and decoded['username'] == photo.user.username:
        photo.name = data['name']
        photo.description = data['description']
        photo.picture = data['url']
        photo.category_id = data['categoryId']
        db_session.add(photo)
        db_session.commit()
        db_session.refresh(photo)
        photo = photo.serialize
        return jsonify(photo), 202
Esempio n. 5
0
def publish():

    if not session.get('is_admin'):
        return redirect(url_for('admin.login'))
    article_id = int(request.args.get('articleId', 0))

    if not article_id:
        return abort(404)

    draft = db_session.query(Draft).filter(
        Draft.article_id == article_id).first()
    article = db_session.query(Article).filter(
        Article.id == article_id).first()

    if draft:
        if not article:
            article = Article(draft.user_id, draft.user_name, draft.title,
                              draft.content)
            article.id = draft.article_id
            db_session.add(article)
        else:
            article.title = draft.title
            article.content = draft.content

        db_session.delete(draft)
        db_session.flush()

    return redirect('/detail?articleId=' + str(article_id))
Esempio n. 6
0
    def _create_objects(self, object_names):
        """
        Create objects from a list of object names.
        :param object_names: list, List of object names
        :return:
        """
        for obj_name in object_names:
            if self.data.get(obj_name):
                data = self.data[obj_name]
                multiple = False
                if isinstance(data, list) or isinstance(data, dict):
                    multiple = True
                table_name = TABLE_NAMES[obj_name]
                object_class = get_class_by_table_name(table_name)

                if object_class:
                    if multiple:
                        # inject product id into data dictionary for objects that need it as a field.
                        if obj_name in self.product_config[PRODUCT_DEPENDENT]:
                            for key, value in data.items():
                                value['product_id'] = self.objects['product_id']
                        self.objects[obj_name] = get_or_create_multiple(object_class, data=data)
                        db_session.add_all(self.objects[obj_name])
                    else:
                        self.objects[obj_name], _ = get_or_create(object_class, name=self.data[obj_name])
                        db_session.add(self.objects[obj_name])
Esempio n. 7
0
def index():
    if request.method == 'GET':
        if 'email' in session:
            return render_template('home.html')
        else:
            return render_template('login.html')

    if request.method == 'POST':
        reqData = request.get_data()
        reqDataJson = json.loads(reqData)

        sSchema = studentschema()
        appSchema = studentapplicationschema()

        studentJson = None
        applicationJson = None

        if 'student' in reqDataJson.keys():
            studentJson = constructStudent(reqDataJson['student'])
        if 'application' in reqDataJson.keys():
            applicationJson = constructApplication(reqDataJson['application'])

        stu = sSchema.load(studentJson, session=db_session).data
        stu.id = session['uid']
        stuapp = appSchema.load(applicationJson, session=db_session).data

        db_session.merge(stu)
        stuapp.s_id = stu.id

        db_session.commit()
        db_session.add(stuapp)
        db_session.commit()
        return json.dumps({'status': 'OK'})
Esempio n. 8
0
def save() :
  userid = session.get('userid')
  username = session.get('username')

  if not userid or not username or not session.get('is_admin'):
    return redirect(url_for('admin.login'))

  title = request.form.get('title')
  content = request.form.get('content')

  if not title or not content :
    tag_chk_list = get_article_taglist(0)
    return render_template('admin/publish.html', active = 'publish', article = None, tag_list = tag_chk_list)

  ## 去掉HTML的背景颜色,防止和现有CSS的背景颜色冲突
  content = htmlHelper.purge_background(content)

  ## 向数据库添加一篇文章
  article = Article(userid, username, '', '');
  db_session.add(article)
  db_session.flush();

  draft = Draft(article.id, userid, username, title, content) 
  db_session.add(draft)
  db_session.flush();

  ## 向数据库添加文章标签
  tag_list = request.form.getlist('tags')
  dao.save_tags(article.id, tag_list)
  return redirect('/admin/draft?draftId=%d' % draft.id)
Esempio n. 9
0
def comment() :
  article_id = request.form.get('articleId') or 0

  if not article_id :
    return jsonify(state=False, message='文章不存在')

  user_id = session.get('userid')
  user_name = session.get('username')
  to_name = request.form.get('toName') or None
  content = request.form.get('content') or None

  if not content :
    return jsonify(state=False, message='评论内容不能为空')
 
  if not user_name or not user_id :
    return jsonify(state=False, message='用户未登录')

  user = db_session.query(User).filter(User.id == user_id).first()
  ## 向数据库添加一条评论
  c = Comment(article_id, user.id, user.name, user.head_url, to_name, content)
  db_session.add(c)
  db_session.flush()

  article_url = 'http://hamilton.duapp.com/detail?articleId=' + str(article_id)
  bmq.send_mail(['*****@*****.**'], 'hamilton上的新回复', '<!--HTML-->\n您有一条新回复需要处理<br/>点击查看:<a href="' + article_url + '">' + article_url + '</a>')

  return jsonify(state=True, message='success')
Esempio n. 10
0
def publish() :

  if not session.get('is_admin'):
    return redirect(url_for('admin.login'))
  article_id = int(request.args.get('articleId', 0))

  if not article_id :
    return abort(404)

  draft = db_session.query(Draft).filter(Draft.article_id == article_id).first()
  article = db_session.query(Article).filter(Article.id == article_id).first()

  if draft :
    if not article :
      article = Article(draft.user_id, draft.user_name, draft.title, draft.content)
      article.id = draft.article_id
      db_session.add(article)
    else :
      article.title = draft.title
      article.content = draft.content

    db_session.delete(draft)
    db_session.flush()
  
  return redirect('/detail?articleId=' + str(article_id))
Esempio n. 11
0
def save_post(title, content):
    # Create the new post
    new_post = Post(title=title, content=content, date=datetime.datetime.now())

    # Add and Save the new post
    db_session.add(new_post)
    db_session.commit()
Esempio n. 12
0
def create_source(source_name):
    logger.debug("### Create source [{}] ###".format(source_name))

    source = DataSource(source_name=source_name)
    db_session.add(source)
    db_session.commit()
    return source.source_id
Esempio n. 13
0
def add_location():
    content = request.get_json()
    r = Restaurant(content['id'], content['title'], content['coords']['latitude'], content['coords']['longitude'], content['google_ratings'], content['types'])
    db_session.add(r)
    db_session.commit()
    db_session.remove()
    return 'success'
Esempio n. 14
0
def save():
    userid = session.get('userid')
    username = session.get('username')

    if not userid or not username or not session.get('is_admin'):
        return redirect(url_for('admin.login'))

    title = request.form.get('title')
    content = request.form.get('content')

    if not title or not content:
        tag_chk_list = get_article_taglist(0)
        return render_template('admin/publish.html',
                               active='publish',
                               article=None,
                               tag_list=tag_chk_list)

    ## 去掉HTML的背景颜色,防止和现有CSS的背景颜色冲突
    content = htmlHelper.purge_background(content)

    ## 向数据库添加一篇文章
    article = Article(userid, username, '', '')
    db_session.add(article)
    db_session.flush()

    draft = Draft(article.id, userid, username, title, content)
    db_session.add(draft)
    db_session.flush()

    ## 向数据库添加文章标签
    tag_list = request.form.getlist('tags')
    dao.save_tags(article.id, tag_list)
    return redirect('/admin/draft?draftId=%d' % draft.id)
Esempio n. 15
0
def create_chart(chart_name):
    logger.debug("### Create chart [{}] ###".format(chart_name))

    chart = Chart(chart_name=chart_name)
    db_session.add(chart)
    db_session.commit()

    return chart.chart_id
Esempio n. 16
0
def signup():
    form = request.json
    new_user = User(
        civilite=form["civilite"],
        firstName=form["firstName"],
        lastName=form["lastName"],
        birthDate=form["birthDate"],
        email=form["email"],
        phone=form["phone"],
        plastaId=form["plastaId"],
        pwd=form["password"],
        group=form["group"],
    )
    try:
        db_session.add(new_user)
        db_session.commit()
    except sqlalchemy.exc.IntegrityError as err:
        duplicated_key = err.orig.msg.split("'")[-2]
        return (
            jsonify(
                {
                    "msg": "{} est déja utilisée. Si vous avez déja un compte et oublié votre mot de passe, cliquer sur 'Renvoi du mot de passe' sur la page de login".format(
                        duplicated_key
                    )
                }
            ),
            422,
        )

    # Send a verification mail
    url_conf = generate_confirmation_token(form["email"])
    msg = Message(
        "Validation de votre inscription à J4U",
        sender="*****@*****.**",
        recipients=[form["email"]],
    )
    msg.html = """
                <p>
                Bonjour,
                </p>
                <p>
                Nous vous remercions pour votre participation au projet « Job For You » (J4U).
                </p>
                <p>
                Suite à votre inscription, voici un email de confirmation. Afin de valider votre compte, il vous suffit de cliquer sur le lien suivant (qui n’est actif que quelques jours) :
                </p>
                <p>
                <a href="{}">Cliquez ici pour confirmer votre adresse email</a>
                </p>
                <p>
                L’équipe J4U
                </p>
                """.format(
        url_conf
    )
    mail.send(msg)
    res = jsonify(success=True)
    return res
Esempio n. 17
0
def save_tags(article_id, tag_list) :

  if not tag_list :
    return None

  for tag_id in tag_list :
    tag_name = db_session.query(Tags.name).filter(Tags.id == tag_id).first()[0]
    db_session.add(TagedArticle(tag_id, article_id, tag_name))
  db_session.flush()
Esempio n. 18
0
def fblogin():
    """ Handles login requests through facebook login"""
    data = request.get_json()
    print "data from request is"
    print data
    message = {}
    message['message'] = "facebook login in received"

    email = data['email']
    print email
    user = helpers.user_by_email(email)
    print user

    if user:
        # create a JWT token to login

        token_data = {
            'iat': datetime.datetime.utcnow(),
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30),
            'username': user.username,
            'userId': user.id,
            'isLoggedIn': True,
        }
        auth_token = jwt.encode(token_data,
                                constants.SECRET_KEY,
                                algorithm='HS256')
        # create a JSON message with JWT and send it to client
        message['auth_token'] = auth_token
        message['success'] = True
        print message
        return jsonify(message), 200

    if not user:
        # create a new User instance from the facebook login credentails, then a JWT login.
        username = data['name']
        new_user = User(username=username, email=email)
        db_session.add(new_user)
        db_session.commit()
        user_with_id = db_session.refresh(new_user)
        message['user'] = user_with_id

        token_data = {
            'iat': datetime.datetime.utcnow(),
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30),
            'username': user_with_id.username,
            'userId': user_with_id.id,
            'isLoggedIn': True,
        }
        auth_token = jwt.encode(token_data,
                                constants.SECRET_KEY,
                                algorithm='HS256')

        message['auth_token'] = auth_token
        message['success'] = True
        print message
        return jsonify(message), 200
Esempio n. 19
0
def signup():
    """ Creates a new User """
    data = request.get_json()

    # make sure all required data is present
    message = {}
    success = ''

    username = data['username']
    password = data['password']
    email = data['email']

    # check for missing data
    if username == '':
        message['error_username'] = "******"
        success = False
    if password == '':
        message['error_password'] = "******"
        success = False
    if email == '':
        message['error_email'] = "email is required"
        success = False
    if success is False:
        message['success'] = False
        return jsonify(errors=message), 200

    # check for valid data
    if not helpers.valid_username(str(username)):
        message['error_username'] = "******"
        success = False
    if helpers.user_by_name(username) is not None:
        message['error_username'] = "******"
        success = False
    if not helpers.valid_password(password):
        message['error_password'] = "******"
        success = False
    if not helpers.valid_email(email):
        message['error_email'] = "Email is not valid"
        success = False
    if helpers.user_by_email(str(email)) is not None:
        message['error_email'] = "Email already in use"
    if success is False:
        message['success'] = False
        return jsonify(errors=message), 200

    # hash the password for db storage
    pw_hash = helpers.make_pw_hash(username, password)
    # create new instance of user
    new_user = User(username, email, pw_hash)
    db_session.add(new_user)
    db_session.commit()
    db_session.refresh(new_user)
    message['success'] = True
    message['user'] = new_user.serialize
    return jsonify(message), 201
Esempio n. 20
0
 def insert_task_data(id, temperature, duration, batch_id):
     try:
         data = TaskDataModel(id=id,
                              timestamp=datetime.now(),
                              temperature=temperature,
                              duration=duration,
                              batch_id=batch_id)
         db_session.add(data)
         db_session.commit()
     except Exception as Err:
         raise Err
Esempio n. 21
0
 def insert_log(log_type, action, message=""):
     try:
         data = LogData(id=uuid.uuid1(),
                        timestamp=datetime.now(),
                        log_type=log_type,
                        action=action,
                        message=message)
         db_session.add(data)
         db_session.commit()
     except Exception as Err:
         raise Err
Esempio n. 22
0
def update():
    form = request.json
    current_user = get_current_user()
    current_user.civilite = form["civilite"]
    current_user.firstName = form["firstName"]
    current_user.lastName = form["lastName"]
    current_user.birthDate = form["birthDate"]
    current_user.email = form["email"]
    current_user.phone = form["phone"]
    current_user.plastaId = form["plastaId"]
    db_session.add(current_user)
    db_session.commit()
    return jsonify(success=True)
Esempio n. 23
0
    def _refreshDividendsDB(self, ticker, force_refresh=False):

        # 1 Use yahoo reader to scrape
        res = []
        dividends = None
        try:
            dividends = yahoo_reader.yahoo_reader.get_dividend(
                ticker, force_refresh)
        except Exception as e:
            logger.exception(
                "Failed to parse dividends for {ticker}".format(ticker=ticker))
            return res

        # 2 Add to TB and return
        for index, row in dividends.iterrows():

            period = row[0]
            dividend = row[1]
            # Check if it exists
            query = stockdatamodel.Dividend.query.filter(
                stockdatamodel.Dividend.ticker == ticker).filter(
                    stockdatamodel.Dividend.period == period)
            if query.count() < 1:
                logger.debug(
                    "Don't have this dividend yet {ticker} {period} ".format(
                        ticker=ticker, period=period))
                d = stockdatamodel.Dividend(
                    ticker=ticker,
                    period=period,
                    dividend=dividend,
                )
                try:
                    db_session.add(d)
                    res.append(d)
                except Exception as e:
                    logger.exception("Failed to add dividend to DB")
            else:
                d = query.first()
                # logger.debug(d)
                # If we need to force refresh update it
                if force_refresh:
                    logger.debug(
                        "We are force refreshing dividend {ticker} {period}".
                        format(ticker=ticker, period=period))
                    d.dividend = dividend
                res.append(d)
        try:
            db_session.commit()
            return res
        except Exception as e:
            logger.exception("Failed to commit dividend to DB")
Esempio n. 24
0
def new_photo():
    """ Creates a new photo """
    headers = request.headers
    data = request.get_json()
    # initialze return message
    message = {}
    success = ''
    # check for valid token
    jwt_token = headers['X-Authorization']
    try:
        jwt.decode(jwt_token, constants.SECRET_KEY)
    except jwt.exceptions.InvalidTokenError:
        message['error'] = 'token is invalid'
        return jsonify(message), 400
    name = data['name']
    description = data['description']
    category_id = data['categoryId']
    url = data['url']
    user_id = data['userId']

    # check for missing data
    if name == '':
        message['error_name'] = "you must provide a name"
        success = False
    if description == '':
        message['error_description'] = "you must provide a description"
        success = False
    if category_id == '':
        message['error_category'] = "please choose a cateogry"
        success = False
    if url == '':
        message['error_picture'] = "provide a url for your picture"
        success = False
    if success is False:
        return jsonify(errors=message), 200

    # validate data
    if not helpers.valid_url(url):
        message['error_picture'] = "you must provide a valid url"
        success = False

    if success is False:
        return jsonify(errors=message), 200

    # create a new photo instance
    newPhoto = Photo(name, description, category_id, url, user_id)
    db_session.add(newPhoto)
    db_session.commit()
    db_session.refresh(newPhoto)
    photo = newPhoto.serialize
    return jsonify(photo), 201
Esempio n. 25
0
def create_follow(from_id, to_id):
    # assume my_id and friend_id are valid
    u = Follow(from_id, to_id)
    db_session.add(u)
    db_session.flush()
    db_session.commit()
    return {
        'success': 1,
        'from_id': u.from_id,
        'to_id': u.u_id,
        'msg': 'success'
    }


#print(create_post(1, 1000, 100, "dsf"))
Esempio n. 26
0
def get_or_create(model, **kwargs):
    """
    Get or create a model instance while preserving integrity.
    :param model: model to get or create.
    :return: tuple, Tuple of instance of the model and boolean reflecting if object was or was not created.
    """
    try:
        return db_session.query(model).filter_by(**kwargs).one(), False
    except NoResultFound:
        try:
            with db_session.begin_nested():
                instance = model(**kwargs)
                db_session.add(instance)
                return instance, True
        except IntegrityError:
            return db_session.query(model).filter_by(**kwargs).one(), False
Esempio n. 27
0
def retrieve_all(surveyId):
    df = get_surveys()
    uois = User.query.filter_by(formDone=False).all()
    for uoi in uois:
        if uoi.surveyId in df["ID"].unique():
            v = df[df["ID"] == uoi.surveyId][df.columns[1:]].values[0]
            f = Features(*v)
            uoi.features = f
            uoi.formDone = True
            db_session.add(uoi)

    db_session.commit()

    if surveyId in df["ID"].unique():
        return True
    return False
Esempio n. 28
0
def create_user(username, password, first, last, img_url="null"):
    if len(password) > 16:
        return {
            'success': 0,
            'id': 'null',
            'msg': 'password is too long, make less than 16'
        }
    u = User(username, password, first, last, img_url)

    # make sure it is not duplicate
    if db_session.query(User).filter(User.username == username).first():
        return {'success': 0, 'id': 'null', 'msg': 'user already exist'}
    db_session.add(u)
    # make sure we update our database is updated with the id
    db_session.flush()
    db_session.commit()
    return {'success': 1, 'id': u.id, 'msg': 'success'}
Esempio n. 29
0
def edit():
    userid = session.get('userid')
    username = session.get('username')

    if not userid or not username or not session.get('is_admin'):
        return redirect(url_for('admin.login'))

    article_id = int(request.args.get('articleId', 0))
    title = request.form.get('title')
    content = request.form.get('content')

    if not article_id:
        return abort(404)

    ## 从数据库取出博客内容
    draft = db_session.query(Draft).filter(
        Draft.article_id == article_id).first()

    if not draft:
        article = db_session.query(Article).filter(
            Article.id == article_id).first()
        if not article:
            return abort(404)
        draft = Draft(article.id, article.user_id, article.user_name,
                      article.title, article.content)
        db_session.add(draft)
        db_session.flush()

    ## 浏览器发送的表单里没有数据,则把编辑页面发送给用户
    if not title or not content:
        tag_list = get_article_taglist(article_id)
        return render_template('admin/publish.html',
                               active='publish',
                               article=draft,
                               tag_list=tag_list)

    ## 表单里有数据,需要更新数据库
    draft.title = title
    draft.content = htmlHelper.purge_background(content)
    db_session.flush()

    ## 更新文章的标签表
    tag_list = request.form.getlist('tags')
    dao.update_tags(article_id, tag_list)
    return redirect('/admin/draft?draftId=%d' % draft.id)
Esempio n. 30
0
def worldseatemp_temp():
    logging.debug("worldseatemp_temp() started")
    source_name = "worldseatemp"

    source_id = DataSource.query.filter(DataSource.source_name == source_name)
    source_id = source_id.all()

    if not source_id:
        source_id = create_source(source_name)
    else:
        source_id = source_id[0].source_id

    temp = get_temp_worldseatemp()

    data = Data(indicator=temp, chart_id=chart_id, source_id=source_id)

    db_session.add(data)
    db_session.commit()
Esempio n. 31
0
def worldseatemp_temp():
    logging.debug("worldseatemp_temp() started")
    source_name = "worldseatemp"

    source_id = DataSource.query.filter(DataSource.source_name == source_name)
    source_id = source_id.all()

    if not source_id:
        source_id = create_source(source_name)
    else:
        source_id = source_id[0].source_id

    temp = get_temp_worldseatemp()

    data = Data(indicator=temp, chart_id=chart_id, source_id=source_id)

    db_session.add(data)
    db_session.commit()
Esempio n. 32
0
def add_abonent():
    """Добавить пользователя"""

    if Abonent.ABONENT_ID not in request.json or not is_valid_abonent_id(
            request.json[Abonent.ABONENT_ID]):
        return create_response(400, False,
                               f"Error in field '{Abonent.ABONENT_ID}'", '')

    if Abonent.ABONENT_NAME not in request.json:
        return create_response(400, False,
                               f"Error in field '{Abonent.ABONENT_NAME}'", '')

    if Abonent.BALANCE not in request.json or not is_valid_amount(
            request.json[Abonent.BALANCE]):
        return create_response(400, False,
                               f"Error in field '{Abonent.BALANCE}'", '')

    if Abonent.HOLDS not in request.json or not is_valid_amount(
            request.json[Abonent.HOLDS]):
        return create_response(400, False, f"Error in field '{Abonent.HOLDS}'",
                               '')

    if Abonent.ACCOUNT_STATUS not in request.json or not isinstance(
            request.json[Abonent.ACCOUNT_STATUS], bool):
        return create_response(400, False,
                               f"Error in field '{Abonent.ACCOUNT_STATUS }'",
                               '')

    account_id = request.json[Abonent.ABONENT_ID]
    account_name = request.json[Abonent.ABONENT_NAME]
    balance = request.json[Abonent.BALANCE]
    holds = request.json[Abonent.HOLDS]
    account_status = request.json[Abonent.ACCOUNT_STATUS]

    abonent = Abonent(account_id, account_name, balance, holds, account_status)
    if Abonent.query.get(account_id) is None:
        # TODO: add retry system
        db_session.add(abonent)
        db_session.commit()
        return create_response(200, True, abonent.serialize,
                               "Successfully added new abonent")
    return create_response(400, False, f"Duplicate key: {account_id}")
Esempio n. 33
0
def insertOrUpdateKeywordByUsers(keyword, values, user_id):
    user_keyword = KeywordByUser.query.filter_by(id_keyword=keyword.id,
                                                 id_user=user_id).first()
    if hasattr(user_keyword, 'id'):
        count = user_keyword.count
        user_keyword.pos_rate = (
            (user_keyword.pos_rate * count) + values['pos']) / (count + 1)
        user_keyword.neg_rate = (
            (user_keyword.neg_rate * count) + values['neg']) / (count + 1)
        user_keyword.neutral_rate = (
            (user_keyword.neutral_rate * count) + values['neu']) / (count + 1)
        user_keyword.count = count + 1
    else:
        user_keyword = KeywordByUser(id_user=user_id,
                                     id_keyword=keyword.id,
                                     pos_rate=values['pos'],
                                     neg_rate=values['neg'],
                                     neutral_rate=values['neu'],
                                     count=1)
        db_session.add(user_keyword)
    db_session.commit()
Esempio n. 34
0
 def _create_base_product(self):
     """
     Creates base product without relationships that require its existence formerly. Needs objects from
     INDEPENDENT object names to exist first. Product is then flushed to the database but not committed.
     :return: product, instance of a product
     """
     product_class = get_class_by_table_name(f'{self.product_type}_product')
     if product_class:
         # build kwargs for product
         product_kwargs = {}
         for field in self.product_config[BASE_FIELDS]:
             if field in self.product_config[SINGLE_RELATIONS]:
                 product_kwargs[field] = self.objects[field]
             else:
                 product_kwargs[field] = self.data[field]
         product, _ = get_or_create(product_class, **product_kwargs)
         db_session.add(product)
         db_session.flush()
         self.objects['product_id'] = product.id
         return product
     raise ValueError('Unknown product class')
Esempio n. 35
0
def edit() :
  userid = session.get('userid')
  username = session.get('username')

  if not userid or not username or not session.get('is_admin'):
    return redirect(url_for('admin.login'))

  article_id = int(request.args.get('articleId', 0))
  title = request.form.get('title')
  content = request.form.get('content')

  if not article_id :
    return abort(404)

  ## 从数据库取出博客内容
  draft = db_session.query(Draft).filter(Draft.article_id == article_id).first()

  if not draft :
    article = db_session.query(Article).filter(Article.id == article_id).first()
    if not article :
      return abort(404)
    draft = Draft(article.id, article.user_id, article.user_name, article.title, article.content)
    db_session.add(draft)
    db_session.flush();

  
  ## 浏览器发送的表单里没有数据,则把编辑页面发送给用户
  if not title or not content :
    tag_list = get_article_taglist(article_id)
    return render_template('admin/publish.html', active = 'publish', article=draft, tag_list = tag_list)

  ## 表单里有数据,需要更新数据库
  draft.title = title
  draft.content = htmlHelper.purge_background(content)
  db_session.flush()

  ## 更新文章的标签表
  tag_list = request.form.getlist('tags')
  dao.update_tags(article_id, tag_list)
  return redirect('/admin/draft?draftId=%d' % draft.id)