def pregame():
    """Let the user choose one out of two random categories."""

    # "GET" method
    if request.method == "GET":

        # if table is empty, insert values
        if Categories.query.get(1) is None:

            # generate two different random categories
            firstcat = randomcategory()
            secondcat = randomcategory()
            while firstcat == secondcat:
                secondcat = randomcategory()

            # update database with new categories
            randomcats = Categories(firstcat, secondcat)
            db.session.add(randomcats)
            db.session.commit()

        # update the table otherwise
        else:

            # generate two different random categories
            Categories.query.get(1).firstcat = randomcategory()
            Categories.query.get(1).secondcat = randomcategory()
            while Categories.query.get(1).firstcat == Categories.query.get(1).secondcat:
                Categories.query.get(1).secondcat = randomcategory()
            db.session.commit()

        # query for categories
        cats = Categories.query.get(1)
        return render_template("pregame.html", cats=cats)

    # "POST" method
    else:

        # if the first category was chosen
        if request.form.get("cat") == "1":
            if Choice.query.get(1) is None:
                keuze = Choice(Categories.query.get(1).firstcat)
                db.session.add(keuze)
                db.session.commit()
            Choice.query.get(1).choice = Categories.query.get(1).firstcat
            db.session.commit()
            return redirect(url_for("question"))

        # if the second category was chosen
        if request.form.get("cat") == "2":
            if Choice.query.get(1) is None:
                keuze = Choice(Categories.query.get(1).secondcat)
                db.session.add(keuze)
                db.session.commit()
            Choice.query.get(1).choice = Categories.query.get(1).secondcat
            db.session.commit()
            return redirect(url_for("question"))
Example #2
0
def dummydata():
    ## Person
    p1 = Person()
    p1.name = "Anna"
    p1.password = "******"
    p1.is_present = True
    p1.role = 0

    p2 = Person()
    p2.name = "Bob"
    p2.password = "******"
    p2.is_present = False
    p2.role = 1

    ## Elec-Rounds
    elec_round = ElectionRound()
    elec_round.title = "Braucht Ihr Pause?"
    elec_round.running = "running"
    elec_round.max_choices_per_person = 1

    ## Choices
    ch1 = Choice()
    ch1.picture = "beer.png"
    ch1.description = "Ja!"
    ch1.counter = 4
    #ch2.elec_round = elec_round

    ch2 = Choice()
    ch2.picture = "working.jpg"
    ch2.description = "Ne, passt..."
    ch2.counter = 2
    ch2.election_round = elec_round

    # RELATIONSHIP (pls work)

    # The example Choice belongs to the first Election Round 
    ch1.election_round = elec_round
    # Anna and Bob both Voted in the first Election Round
    p1.voted_in_election_round.append(elec_round)
    p2.voted_in_election_round.append(elec_round)
    # Anna has Bobs Vote
    p1.received_proxy_vote.append(p2)

    session.add(p1)
    session.add(p2)
    session.add(elec_round)
    session.add(ch1)
    session.add(ch2)

    session.commit()
def create_choice(data: dict) -> str:
    if not 'description' in data:
        return Response.wrong_format(
            json.dumps({'message': 'description missing'}))
    if not 'election_round_id' in data:

        return Response.wrong_format(
            json.dumps({'message': 'electionid missing'}))

    if 'picture' in data:
        if data['picture'].endswith('=='):
            picture = data['picture']
        else:
            return Response.wrong_format({"message": "picture is not Base64"})
    else:
        picture = ''

    choice = Choice(description=data['description'],
                    counter=0,
                    picture=picture,
                    election_round_id=data['election_round_id'])
    session.add(choice)
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok(
        json.dumps({
            'id': choice.id,
            'description': choice.description
        }))
Example #4
0
def choice_add(request):
    question = Question.objects.get(id=request.session['current_question'])
    newChoice = Choice()
    newChoice.choice_text = request.POST["choice_text"]
    question.choice_set.add(newChoice)
    newChoice.save()
    question.save()
    return redirect('admin-choice-add-view')
Example #5
0
    async def on_post(self, req, resp):
        """
        postの場合は受け取ったデータをQuestionテーブルに追加する。
        """
        data = await req.media()
        error_messages = list()
        """ エラー処理 """
        if data.get('question_text') is None:
            error_messages.append('質問内容が入力されていません。')

        if data.get('date') is None or data.get('time') is None:
            error_messages.append('公開日時が入力されていません。')

        # 配列として受け取ったフォームはget_list()で取得する
        choices = data.get_list('choices[]')
        votes = data.get_list('votes[]')

        if len(choices) == 0 or len(votes) == 0 or len(choices) != len(votes):
            error_messages.append('選択肢内容に入力されていない項目があります。')

        if len(choices) < 1:
            error_messages.append('選択肢は2つ以上必要です。')

        # 何かしらエラーがあればリダイレクト
        if len(error_messages) != 0:
            resp.content = api.template('add_question.html',
                                        error_messages=error_messages,
                                        date=datetime.now())
            return
        """ テーブルにQuestionを追加 """
        # 公開日時をセパレートしてint型のリストに変換
        date = [int(d) for d in data.get('date').split('-')]
        time = [int(t) for t in data.get('time').split(':')]

        # question作成
        question = Question(
            data.get('question_text'),
            datetime(date[0], date[1], date[2], time[0], time[1], time[2]))
        # question追加
        db.session.add(question)
        db.session.commit()
        """ テーブルにChoicesを追加 """
        # まず外部キーとなるQuestion.idを取得
        foreign_key = question.id
        q_choices = list()

        for i, choice in enumerate(choices):
            # choice作成
            q_choices.append(Choice(foreign_key, choice, int(votes[i])))

        # choice追加
        db.session.add_all(q_choices)
        db.session.commit()

        db.session.close()

        api.redirect(resp, '/admin_top')
Example #6
0
async def process_start_command(message: types.Message):
    user_id = message.from_user.id
    mention = message.from_user.get_mention()
    try:
        reg = User(id=user_id, name=mention, presence=False)
        choice_init = Choice(id=user_id, Name=mention)
        await reg.save()
        await choice_init.save()
    finally:
        return await message.reply(MESSAGES["start_message"])
Example #7
0
 def parse_choice(self, metadata, stack):
     from .ContextParser import ContextParser
     match = regex_choice.match(metadata.line)
     if match:
         description = match["choice"]
         choice = Choice(description, metadata)
         self.choice = choice
         self.menu.add_choice(choice)
         parser = ContextParser(self, metadata)
         stack.push(parser)
         return True
     return False
Example #8
0
 def all(self):
     if request.method == 'GET':
         surveys = Survey.all()
         return jsonify([s.to_dict() for s in surveys])
     elif request.method == 'POST':
         data = request.get_json()
         survey = Survey(name = data['name'])
         questions = []
         for q in data['questions']:
             question = Question(text = q['text'])
             question.choices = [Choice(text = c) for c in q['choices']]
             questions.append(question)
         survey.questions = questions
         survey.save()
         return jsonify(survey.to_dict()), 201
    def __row_to_contest(self, row):
        contest = Contest()
        contest.title = row[self.__csv_format['QUESTION_COL_INDEX']]

        for index in self.__csv_format['OPTIONS_COL_INDEXES']:
            option = Choice()
            option.title = row[index]
            contest.options.append(option)

            if index == self.__csv_format['RESPONSE_COL_INDEX']:
                contest.response_index = len(contest.options) - 1

        if contest.response_index is None:
            raise Exception('Response index must be in the options list')

        return contest
Example #10
0
    async def on_post(self, req, resp):
        """
        postの場合は受け取ったデータをQuestionテーブルに追加する。
        """
        data = await req.media()
        error_messages = list()

        # もし何も入力されていない場合
        if data.get('choice_text') is None:
            error_messages.append('選択肢が入力されていません。')
            questions = db.session.query(Question.id, Question.question_text)
            resp.content = api.template('add_choice.html',
                                        error_messages=error_messages,
                                        questions=questions)
            return

        # テーブルに追加
        choice = Choice(data.get('question'), data.get('choice_text'))
        db.session.add(choice)
        db.session.commit()
        db.session.close()

        api.redirect(resp, '/admin_top')
Example #11
0
def create_a_poll(request, survey_id):
    # create a poll in a survey
    # get questions from input
    # redirect to craetPollPage

    logging.debug(request.POST)
    question = request.POST['Question0']
    choice_list = request.POST.getlist('Field1')
    s = get_object_or_404(Survey, pk=survey_id)
    # check if user correct
    if not s.author == request.user.username:
        return

    p = Poll(survey=s, question=question)
    p.save()
    # get choice from form input
    logging.debug(choice_list)
    for c in choice_list:
        if c:
            logging.debug(c)
            choice = Choice(poll=p, choice=c, votes=0)
            choice.save()

    return HttpResponseRedirect('createPollPage')
p1.role = 0

p2 = Person()
p2.name = "Bob"
p2.password = "******"
p2.is_present = False
p2.role = 1

## Elec-Rounds
elec_round = ElectionRound()
elec_round.title = "Braucht Ihr Pause?"
elec_round.running = "running"
elec_round.max_choices_per_person = 1

## Choices
ch1 = Choice()
ch1.picture = "beer.png"
ch1.description = "Ja!"
ch1.counter = 4
#ch2.elec_round = elec_round

ch2 = Choice()
ch2.picture = "working.jpg"
ch2.description = "Ne, passt..."
ch2.counter = 2
ch2.election_round = elec_round

# RELATIONSHIP (pls work)

# The example Choice belongs to the first Election Round
ch1.election_round = elec_round
Example #13
0
from create_db import engine
from models import Pizza, Choice, Base
import json
import argparse

session = sessionmaker()
session.configure(bind=engine)
s = session()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("filename")
    args = parser.parse_args()

    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)

    with open(args.filename, "r") as file:
        catalog = json.load(file)

    for pizza in catalog:
        new_pizza = Pizza(title=pizza['title'],
                          description=pizza['description'])
        for choice in pizza['choices']:
            new_choice = Choice(title=choice['title'],
                                price=int(choice['price']))
            new_pizza.choices.append(new_choice)
        s.add(new_pizza)

    s.commit()
Example #14
0
    u = User()
    u.displayname = "Testkonto 1"
    u.email = "*****@*****.**"
    u.password = "******"
    u.save()

    p1 = Poll()
    p1.name = "Testpoll 1"
    p1.number = "+46766862842"
    p1.allow_duplicate_answers = True
    p1.allow_multiple_choices = True
    p1.owner = u
    p1.save()

    c1 = Choice()
    c1.poll = p1
    c1.name = "01"
    c1.description = "Bidrag nr. 1 - Bä bä vita lamm"
    c1.save()

    c2 = Choice()
    c2.poll = p1
    c2.name = "02"
    c2.description = "Bidrag nr. 2 - Blinka lilla stjärna"
    c2.save()

    c3 = Choice()
    c3.poll = p1
    c3.name = "03"
    c3.description = "Bidrag nr. 3 - Björnen sover"
Example #15
0
async def index(request):
    ch = Choice(name="linxiao", status=JobStatus.Leave)
    await ch.save()
    return json({"message": "前后端可选项同步测试。"})
Example #16
0
from app import db
from models import Pizza, Choice


def load_catalog(filename):

    with open(filename) as file_handler:
        return json.loads(file_handler.read())


if __name__ == '__main__':

    catalog_filename = sys.argv[1] if len(sys.argv) > 1 else 'catalog.json'

    catalog = list()

    for entry in load_catalog(catalog_filename):

        pizza = Pizza(title=entry['title'], description=entry['description'])

        for choice in entry['choices']:

            pizza.choices.append(
                Choice(title=choice['title'], price=choice['price']))

        catalog.append(pizza)

    db.session.add_all(catalog)
    db.session.commit()
Example #17
0
def create_choice(db:Session, qid: int, choice: schema.ChoiceCreate):
	obj = Choice(**choice.dict(), question_id=qid)
	db.add(obj)
	db.commit()
	return obj
Example #18
0
import json
from app import db
from models import Pizza, Choice
from db.catalog import catalog

choice_id = 1
for pizza_id, pizza_data in enumerate(catalog, 1):
    pizza = Pizza(
                id=pizza_id,
                title=pizza_data['title'],
                description=pizza_data['description'])
    print(pizza_id, pizza)
    db.session.add(pizza)
    for choice_data in pizza_data['choices']:
        choice_id += 1
        choice = Choice(
                    id=choice_id,
                    title=choice_data['title'],
                    price=choice_data['price'],
                    pizza_id=pizza_id)
        print(choice_id, choice)
        db.session.add(choice)
db.session.commit()