def obj_create(self, bundle, request=None, **kwargs):
     suggestion =  bundle.data['suggestion']
     comment =  bundle.data['comments']
     email =  bundle.data['email']
     suggestion = Suggestion(suggestion=suggestion,comment=comment,email=email)
     suggestion.save()
     bundle.obj=suggestion
     return bundle
示例#2
0
def add_fake_data(number_users):
    """Add fake data to the database."""
    User.generate_fake(count=number_users)
    Document.generate_fake(count=number_users)
    Suggestion.generate_fake(count=number_users)
    Saved.generate_fake()
    Tag.generate_fake(count=number_users)
    Tagged.generate_fake()
示例#3
0
def reset_suggestion(suggestion: Suggestion, session=None):
    """
    Восстанавливает предложку в состояние новой
    :param suggestion:
    :return:
    """
    suggestion.reset_to_new()
    markup = create_admin_reply_markup(suggestion)
    rerender_suggestion(suggestion, markup)
 def obj_create(self, bundle, request=None, **kwargs):
     suggestion = bundle.data['suggestion']
     comments =bundle.data['comments']
     email = bundle.data['email']
     location_id = bundle.data['location_id']
     suggestion = Suggestion(location_id=location_id,suggestion=suggestion,comments=comments,email=email)
     suggestion.save()
     bundle.obj = suggestion
     return bundle
示例#5
0
def suggestions():
    user = {'username': '******'}
    posts = [{
        'body': 'Gets your suggestions. List previous suggestions'
    }, {
        'body': 'To demonstate basic database operations.'
    }, {
        'body': 'SQLAlchemy, AWS RDS (MySQL)'
    }]

    form = BasriSuggestionsForm()
    if form.validate_on_submit():
        flash('Others have provided the following so far...')
        suggestions_retreived_from_db = Suggestion.query.all()
        for s in suggestions_retreived_from_db:
            flash(s)
        flash('Your suggestions: {}'.format(form.Suggestions.data))
        suggestion = Suggestion(body=form.Suggestions.data)
        db.session.add(suggestion)
        db.session.commit()
        return render_template('index_Suggestions.html',
                               title='Home',
                               user=user,
                               posts=posts)
    return render_template('suggestions.html',
                           title='Basri Suggestions',
                           form=form)
    def test_edit_suggestion(self):
        """Test suggestion of an edit"""
        r = Resource(name='test_edit')
        db.session.add(r)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()

        r_added = Resource.query.filter_by(name='test_edit').first()
        s_text = "The phone number of this establishment is incorrect: it should be 212-346-5927"
        s_contact_name = "Anonymous Helper"
        s_contact_email = "*****@*****.**"
        s_contact_number = "000-001-0101"
        s_timestamp = datetime.now(pytz.timezone('US/Eastern'))
        suggestion = Suggestion(resource_id=r_added.id,
                                suggestion_text=s_text,
                                read=1,
                                contact_name=s_contact_name,
                                contact_email=s_contact_email,
                                contact_phone_number=s_contact_number,
                                submission_time=s_timestamp)
        db.session.add(suggestion)
        db.session.commit()

        r_in_table = Suggestion.query.filter_by(suggestion_text=s_text).first()
        self.assertTrue(r_in_table is not None)
        self.assertTrue(r_in_table.suggestion_text == s_text)
        self.assertTrue(r_in_table.resource_id == r_added.id)
        self.assertTrue(r_in_table.read == 1)
        self.assertTrue(r_in_table.contact_phone_number == s_contact_number)
        self.assertTrue(r_in_table.submission_time is not None)
        self.assertTrue(r_in_table.contact_name == s_contact_name)
        self.assertTrue(r_in_table.contact_email == s_contact_email)
    def test_insertion_suggestion(self):
        """Test suggestion of an insertion"""
        s_text = "Name: Taco Time \n Address: 123 45th Street"
        s_contact_name = "John Doe"
        s_contact_number = "123-456-7890"
        s_contact_email = "*****@*****.**"
        s_timestamp = datetime.now(pytz.timezone('US/Eastern'))
        suggestion = Suggestion(suggestion_text=s_text,
                                read=0,
                                contact_name=s_contact_name,
                                contact_email=s_contact_email,
                                contact_phone_number=s_contact_number,
                                submission_time=s_timestamp)
        db.session.add(suggestion)
        db.session.commit()

        r_in_table = Suggestion.query.filter_by(suggestion_text=s_text).first()
        self.assertTrue(r_in_table is not None)
        self.assertTrue(r_in_table.suggestion_text == s_text)
        self.assertTrue(r_in_table.resource_id is None)
        self.assertTrue(r_in_table.read == 0)
        self.assertTrue(r_in_table.contact_phone_number == s_contact_number)
        self.assertTrue(r_in_table.submission_time is not None)
        self.assertTrue(r_in_table.contact_name == s_contact_name)
        self.assertTrue(r_in_table.contact_email == s_contact_email)
示例#8
0
def apply_to_entity(json_dict: dict, entity):
    entity_attributes = [a for a in dir(entity) if not a.startswith('__')]
    prohibited = ['id', 'routing_id', 'mapped_session_id']
    not_nullable_col = [
        col.name for col in entity.__table__.c
        if not col.nullable and col.name not in prohibited
    ]

    # all not nullable columns are set
    for c in not_nullable_col:
        if c not in json_dict:
            raise ValueError(f"Mandatory column '{c}' is missing")

    # handle geom fields (points and polygons)
    if 'geom' in entity_attributes:
        json_dict['geom'] = create_point(**json_dict['geom'])
    if 'where_clicked_geom' in entity_attributes and 'where_clicked_geom' in json_dict:
        json_dict['where_clicked_geom'] = create_point(
            **json_dict['where_clicked_geom'])
    bbox_field_names = [
        b for b in entity_attributes
        if 'bbox' in b and 'geom' in b and b in json_dict
    ]
    for bbox_name in bbox_field_names:
        json_dict[bbox_name] = _create_bbox(**json_dict[bbox_name])

    # Handle fancy routing TextWithSuggestion
    if 'origin_text_box_history' in entity_attributes:
        json_dict['origin_text_box_history'] = apply_to_entity(
            json_dict['origin_text_box_history'], RoutingOrigin())
    if 'destination_text_box_history' in entity_attributes:
        json_dict['destination_text_box_history'] = apply_to_entity(
            json_dict['destination_text_box_history'], RoutingDestination())

    # Handle text_with_suggestion
    # suggestion table references back to text_with_suggestion
    if 'text_with_suggestion' in entity_attributes and not isinstance(
            entity, Suggestion):
        json_dict['text_with_suggestion'] = [
            apply_to_entity(tws, TextWithSuggestion())
            for tws in json_dict['text_with_suggestion']
        ]
    # Suggestions are not mandatory for a TextWithSuggestion entity
    if 'suggestions' in entity_attributes and 'suggestions' in json_dict:
        json_dict['suggestions'] = [
            apply_to_entity(sug, Suggestion())
            for sug in json_dict['suggestions']
        ]

    for key in entity_attributes:
        if key not in prohibited and key in json_dict:
            # transform date for columns(!) of type datetime > check needed as also relations can be set here
            if key in entity.__table__.c and str(
                    entity.__table__.c[key].type) == 'DATETIME':
                setattr(entity, key, time_to_timestamp(json_dict[key]))
            else:
                setattr(entity, key, json_dict[key])
    return entity
示例#9
0
def render_suggestion_text(suggestion: Suggestion):
    """
    Создает текст предложки

    :param suggestion: Предложка
    :return: Тест предложки
    """
    # Основа: заголовок и отправитель
    text = t("app.admin.suggestion.head")
    text += "\n\n"
    # Проверить будет ли работать ссылка на пользователя без юзернейма
    # if not suggestion.user_is_public():
    #     # Отправитель не имеет юзернейма
    #     text += messages.SUGGESTION_FROM % {
    #         "user_title": suggestion.user_title
    #     }
    # else:
    # # Отправитель публичен
    text += t("app.admin.suggestion.from.url",
              user_id=suggestion.user_id,
              user_title=suggestion.user_title)
    # Если отправитель переслал пост из другого канала или от другого пользователя,
    # добавляем информацию об этом в предложку
    if suggestion.is_forward():
        text += "\n"
        if not suggestion.forwarded_is_public():
            # Автор исходного поста не имеет юзернейма
            text += t("app.admin.suggestion.forwarded_from.plain",
                      forwarded_user_title=suggestion.forwarded_from_title)
        else:
            # Автор исходного поста публичен
            text += t("app.admin.suggestion.forwarded_from.url",
                      forwarded_user_id=suggestion.forwarded_from_username,
                      forwarded_user_title=suggestion.forwarded_from_title)
    # Если по предложке уже есть решение, то отображаем его
    if suggestion.decision is not None:
        text += "\n\n"
        text += render_decision(suggestion.decision)
        # Если есть ссылка на пост, то добавляем ее
        # Ссылка на пост может быть только если есть решение
        if suggestion.channel_post_id is not None:
            text += "\n"
            text += render_post_url(suggestion.channel_post_id)
    return text
示例#10
0
def suggestion():
    form = SuggestionForm()
    if form.validate_on_submit():
        data = form.data
        suggestion = Suggestion(name=data["name"],
                                email=data["email"],
                                suggestion=data["suggestion"])
        db.session.add(suggestion)
        db.session.commit()
        flash("您的建议我们已收到,感谢您的提供!", "ok")
        return redirect(url_for("foreground.suggestion"))
    return render_template("foreground/suggestion_list.html", form=form)
示例#11
0
def contact():
    """
    联系我们
    """
    form = SuggetionForm()  # 实例化SuggestionForm类
    if form.validate_on_submit():  # 判断用户是否提交表单
        data = form.data  # 接收用户提交的数据
        # 为属性赋值
        suggestion = Suggestion(
            name=data["name"],
            email=data["email"],
            content=data["content"],
        )
        db.session.add(suggestion)  # 添加数据
        db.session.commit()  # 提交数据
        flash("发送成功!", "ok")  # 用flask存储发送成功消息
    return render_template('home/contact.html', form=form)  # 渲染模板,并传递表单数据
示例#12
0
def contribute():
    if request.method == 'POST':

        form_text = request.form['text']
        form_title = request.form['title']
        form_firstname = request.form['first_name']

        new = Suggestion(
            form_title,
            form_text,
            form_firstname
        )
        db.session.add(new)
        db.session.commit()

        return render_template('thanks.html')
    else:
        return render_template('contribute.html')
示例#13
0
def suggestions(request):

    if request.method == 'GET':
        # If the method is get, then just display the suggestion page
        return render(request, 'suggestions.html', {
            'title': 'Suggestions',
            'form': SuggestionForm()
        })
    else:
        # If the method is post, then store the value
        form = SuggestionForm(request.POST)
        if form.is_valid():
            suggestion = Suggestion()
            suggestion.save_suggestion(request.POST)
            suggestion.save()

            return redirect('/all_suggestions/')
示例#14
0
def catch_photo(message: TelebotMessage, session=None):
    # Проверяем, что сообщение содержит изображение
    if len(message.photo) == 0:
        bot.send_message(message.chat.id, t("app.bot.user.wrong_content"))
        return
    # Создаем новую предложку
    suggestion = Suggestion()
    suggestion.state = Suggestion.STATE_NEW
    # Используем последнее фото с конца (наибольшее разрешение)
    suggestion.file_id = message.photo[-1].file_id
    # Сохраняем отправителя
    suggestion.user_title = get_full_name(message.from_user)
    suggestion.user_id = message.from_user.id
    suggestion.user_username = message.from_user.username
    # Сохраняем идентификатор сообщения в чате пользователя с ботом - понадобится чтобы бот
    # реплайнул на сообщение если его опубликуют
    suggestion.user_message_id = message.message_id
    # Проверяем, пользователь создал сообщение сам или переслал его
    if message.forward_from is not None or message.forward_from_chat is not None:
        if message.forward_from_chat is None:
            # Переслано от пользователя
            suggestion.forwarded_from_id = message.forward_from.id
            suggestion.forwarded_from_username = message.forward_from.username
            suggestion.forwarded_from_title = get_full_name(
                message.forward_from)
        else:
            # Переслано из канала
            suggestion.forwarded_from_id = message.forward_from_chat.id
            suggestion.forwarded_from_username = message.forward_from_chat.username
            suggestion.forwarded_from_title = message.forward_from_chat.title
    # Сохраняем предложку в базе
    session.add(suggestion)
    session.flush()
    # Создаем текст и кнопки для предложки
    admin_message = render_suggestion_text(suggestion)
    markup = create_admin_reply_markup(suggestion)
    # Отправляем предложку админу
    suggestion_message = bot.send_photo(config.APP_BOT_ADMIN_ID,
                                        suggestion.file_id,
                                        admin_message,
                                        reply_markup=markup,
                                        parse_mode="HTML")
    # Сохраняем идентификатор сообщения с предложкой
    suggestion.admin_message_id = suggestion_message.message_id
    # Отправляем пользователю сообщение о том, что его предложка отправлена
    bot.send_message(message.chat.id, t("app.bot.user.posted"))