コード例 #1
0
ファイル: hello.py プロジェクト: 72L/72L.github.io
def savefilters():
	if request.method == 'POST':
		db_session.query(User).filter(User.email == request.form['email']).update({User.filters: request.form['filters']})
		db_session.commit()
		return 'filters saved'
	else:
		return db_session.query(User).filter(User.email == request.args.get('email')  )[0].filters
コード例 #2
0
ファイル: app.py プロジェクト: ribbskott/SwimCoachAPI
def create_club():
    if not check_auth(request):
        abort(403)
    idclub = "0"
    name = ""
    description = ""
    if not request.json or not 'name' in request.json:
        abort(400)
    if not request.json or not 'description' in request.json:
        abort(400)
    if 'idclub' in request.json:
        idclub = request.json['idclub']
    if 'name' in request.json:
        name = request.json['name']
    if 'description' in request.json:
        description = request.json['description']
    club = Club(name=name, description=description)
    if str(idclub) != "0":
        db_session.query(Club).filter_by(idclub=int(idclub)).update({"name": name, "description": description})
        db_session.commit()
    else:
        db_session.add(club)
        db_session.commit()

    return jsonify({"status": "OK"})
コード例 #3
0
ファイル: app.py プロジェクト: ribbskott/SwimCoachAPI
def get_results(idathlete):
    if not check_auth(request):
        abort(403)
    retResults = {"trainingresults": []}
    if request.method == 'GET':
        trainingresults = db_session.query(TrainingResult).filter_by(id=idathlete).join(TrainingSession).order_by(TrainingResult.resulttype)

        for training_result in trainingresults:
            retResults["trainingresults"].append({"result_type":training_result.resulttype,
                               "timeresult": training_result.timeresult,
                               "achievedonsession":training_result.achievedonsession.id,
                               "sessionname": training_result.achievedonsession.name,
                               "achievedondate":str(training_result.achievedonsession.fromtime.isoformat())})
    if request.method == 'PUT':
        if not request.json:
            abort(400)
        training_result = TrainingResult()
        training_result.achievedonsession = request.json["trainingsession"]
        training_result.athlete_id = request.json["athlete"]
        training_result.resulttype = request.json["resulttype"]
        training_result.timeresult = request.json["timeresult"]

        db_session.commit()

    return make_response(jsonify(retResults),200)
コード例 #4
0
ファイル: jokedbapp.py プロジェクト: BL-Labs/jokedbapp
def tweet_joke(joke_id):
  if session['logged_in'] != True:
    abort(401)
  else:
    j = Joke.query.get(joke_id)
    if not j:
      abort(404)

    # Make temp file
    fn, attribution = _render_joke_to_file(j)

    if not j.published_at:
      #publish to tumblr first
      user_id = session['logged_in_user']
      u = User.query.get(user_id)
      if fn:
#        adapted = tumblr_imagepost(j, fn, attribution=attribution, url=url_for("display_joke", joke_id=j.id))
        adapted = tumblr_imagepost(j, fn, attribution=attribution)
        if adapted:
          adapted.published_by_id = u.id
          db_session.add(adapted)
          db_session.add(u)
          db_session.commit()
          flash("Published to {0}/{1}".format(blog, j.tumblr_id))
    
    tumblr_id = j.tumblr_id
    tweet_text, resp = twitter_imagepost(j, fn, tumblr_id = tumblr_id)
    if resp:
      flash(u"Successfully tweeted -> <a href=\"https://twitter.com/VictorianHumour/status/{1}\">'{0}'</a>".format(tweet_text, str(resp['id'])))
      j.twitter_id = resp['id']
      db_session.add(j)
      db_session.commit()
    return redirect(url_for('display_joke', joke_id=j.id))
コード例 #5
0
 def changeDiagnoseStatus(cls,diagnoseId,status):
     if diagnoseId and status:
         diagnose=Diagnose.getDiagnoseById(diagnoseId)
         if diagnose:
             diagnose.status=status
             session.commit()
             session.flush()
コード例 #6
0
ファイル: library.py プロジェクト: DimaWittmann/library
def book(bID):
    form = UpdateBookForm(request.form)
    authors = db_session.query(Author).all()
    form.authors.choices = [(i, authors[i - 1]) for i in xrange(1, len(authors) + 1)]
    selected_book = Book.query.filter(Book.id == bID).one()
    if request.method == 'GET':
        authors = selected_book.authors
        return render_template("book.html", authors=authors, \
               book=selected_book, form=form)
    elif request.method == 'POST' and form.validate():
        selected_book.title = form.new_title.data
        authors = request.form.getlist('authors')
        authors = Author.query.filter(Author.id.in_(authors)).all()
        for author in authors:
            if author in selected_book.authors:
                selected_book.authors.remove(author)
            else:
                selected_book.authors.append(author)
        db_session.commit()
        return redirect(url_for("book", bID=bID))
    elif request.method == 'DELETE':
        flash('{book} is deleted'.format(book=selected_book.title))
        db_session.delete(selected_book)
        db_session.commit()
        return url_for('index')
コード例 #7
0
ファイル: slides.py プロジェクト: addonis1990/slides-moztn
def update_slide():
    """
    Updates a slide.
    """
    current_app.logger.debug("debug updateSlide")
    message = isValidURL(request.form['url'])
    if message is not None:
        return render_template(
            'admin.html',
            categories=category_controller.list(),
            status=False,
            message=message
        )
    if not request.form['screenshot']:
      screenshot = "img/badge-reserved.jpg"
    else:
      screenshot = request.form['screenshot']
    slide_id = request.form['id']
    s = SlideModel.query.get(slide_id)
    s.title = request.form['title']
    s.description = request.form['description']
    s.url = request.form['url']
    s.category = request.form['categorie']
    s.screenshot = screenshot
    db_session.add(s)
    db_session.commit()
    status = True

    return render_template(
        'admin.html',
        categories=category_controller.list(),
        status=status,
        action='updated'
    )
コード例 #8
0
ファイル: mpeds_coder.py プロジェクト: alexhanna/mpeds-coder
def getCodes():
    aid  = int(request.args.get('article'))
    l_i  = 0

    try:
        ## load current values
        curr = db_session.query(CodeFirstPass).filter_by(coder_id = current_user.id, article_id = aid).all()
        cd   = {}

        for c in curr:
            ## these will occur only once
            if c.variable in sv:
                cd[c.variable] = c.value
            else:
                ## if they've seen this article before, note which pass it is
                if c.variable == 'load':
                    l_i = int(c.value) + 1

                ## stash in array
                if c.variable not in cd:
                    cd[c.variable] = []

                cd[c.variable].append( [c.value, c.text] )

        ## insert row for every time they load the article
        ## to measure how much time it takes to read the article
        load = CodeFirstPass(aid, "load", l_i, current_user.id)
        db_session.add(load)
        db_session.commit()

        return jsonify(cd)
    except:
        return make_response("", 404)
コード例 #9
0
ファイル: talons.py プロジェクト: zg/talons
    def on_post(self, req, resp):
        url = req.get_param('url')
        if url is not None:
            # generate a new job ID, insert it into the database, return the job ID to the client
            new_id = _generate_id()
            priority = req.get_param('priority') if req.get_param('priority') is not None else 3
            db_session.add(Job(id=new_id,status='INCOMPLETE',url=url,priority=priority,result=''))
            db_session.commit()

            # immediately tell them the job ID
            resp.data = json.dumps({'job-id':new_id})
            resp.status = falcon.HTTP_200

            # in the event that more than one requests are submitted before
            # we get to this point, this means the scraper will decide which
            # one to work with first

            # look for the most important job to do next
            next_job = db_session.query(Job).filter(Job.status == 'INCOMPLETE').order_by(desc(Job.priority),desc(Job.created)).first()
            if next_job is not None:
                # set the job as in-progress
                db_session.query(Job).filter(Job.id == next_job.id).update({"status":'IN_PROGRESS'})
                try:
                    # get the data, timeout at 30 minutes
                    response = urllib2.urlopen(next_job.url,timeout=30*60)
                    # submit the results to the database
                    db_session.query(Job).filter(Job.id == next_job.id).update({"result":response.read(),"status":'COMPLETED'})
                except urllib2.URLError, e:
                    # Python 2.6
                    if isinstance(e.reason, socket.timeout):
                        db_session.query(Job).filter(Job.id == next_job.id).update({"status":'INCOMPLETE'})
                    else:
                        # reraise the original error
                        raise
コード例 #10
0
ファイル: main.py プロジェクト: agamaloni/anyway
def updatebyemail():
    jsonData = request.get_json(force=True)
    emailaddress = str(jsonData['address'])
    fname = (jsonData['fname']).encode("utf8")
    lname = (jsonData['lname']).encode("utf8")

    if len(fname)>40:
        return  jsonify(respo='First name to long')
    if len(lname)>40:
        return  jsonify(respo='Last name to long')
    if len(emailaddress)>40:
        return jsonify(respo='Email too long', emailaddress = emailaddress)
    user_exists = db_session.query(User).filter(User.email == emailaddress)
    if user_exists.count()==0:
        user = User(email = emailaddress, first_name = fname.decode("utf8"), last_name = lname.decode("utf8"), new_features_subscription=True)
        db_session.add(user)
        db_session.commit()
        return jsonify(respo='Subscription saved', )
    else:
        user_exists = user_exists.first()
        if user_exists.new_features_subscription==False:
            user_exists.new_features_subscription = True
            db_session.add(user_exists)
            db_session.commit()
            return jsonify(respo='Subscription saved', )
        else:
            return jsonify(respo='Subscription already exist', )
コード例 #11
0
ファイル: mpeds_coder.py プロジェクト: alexhanna/mpeds-coder
def delCode(pn):
    """ Deletes a record from first or second pass codings. """
    if False:
        pass
    elif pn == '1':
        a = db_session.query(CodeFirstPass).filter_by(
            article_id = request.args.get('article'),
            variable   = request.args.get('variable'),
            value      = request.args.get('value'),
            coder_id   = current_user.id
        ).all()
    elif pn == '2':
        a = db_session.query(CodeSecondPass).filter_by(
            article_id = request.args.get('article'),
            variable   = request.args.get('variable'),
            value      = request.args.get('value'),
            event_id   = request.args.get('event'),
            coder_id   = current_user.id
        ).all()
    else:
        return make_response("Invalid model", 404)

    if len(a) > 0:
        for o in a:
            db_session.delete(o)

        db_session.commit()

        return jsonify(result={"status": 200})
    else:
        return make_response("", 404)
コード例 #12
0
ファイル: controller.py プロジェクト: luliena01/OneRoom
	def post(self):
		try:
			args = self.reqparse.parse_args()

			email = args['id']
			query = db_session.query(models.User).filter(models.User.email == email)
			user = query.one_or_none()

			if user is None:
				# return {'status': 'error', 'code': error_code.Login.NOT_FOUND_ID, 'message': error_code.Login.NOT_FOUND_ID.message()}
				return Response.error(error_code.Login.NOT_FOUND_ID)

			if not sha256_crypt.verify(str(args['password']), user.password_hash):
				# return {'status': 'error', 'code': error_code.Login.WRONG_PASSWORD, 'message': error_code.Login.WRONG_PASSWORD.message()}
				return Response.error(error_code.Login.WRONG_PASSWORD)

			if user.confirmed is False:
				return Response.error(error_code.Login.NOT_CONFORMED)

			user.last_seen = datetime.now()
			db_session.commit()

			session.clear()
			session[Session.LOGIN_SESSION] = sha256_crypt.encrypt(str(user.code + user.password_hash))
			session[Session.USER_SESSION] = user.code
			session[Session.ADMIN_SESSION] = decorators.is_admin(user.code)

			current_app.logger.info("Login - " + email)

			return Response.ok()
		except Exception as e:
			current_app.logger.error(str(e))
			return Response.error(error_code.Global.UNKOWN)
コード例 #13
0
ファイル: controller.py プロジェクト: luliena01/OneRoom
	def post(self):
		try:
			args = self.reqparse.parse_args()

			email = args['email']
			query = db_session.query(models.User).filter(models.User.email == email)
			user = query.one_or_none()

			if user is not None:
				current_app.logger.warning("Already register id : " + email)
				return Response.error(error_code.Login.ALREADY_REGISTER)

			new_user = models.User(code=generate_uuid(), email=email, password_hash=sha256_crypt.encrypt(str(args['password'])), user_name=args['user_name'], role_id=args['role'],
								   room=args['room'], phone=args['phone'])
			db_session.add(new_user)
			db_session.commit()

			current_app.logger.info("Register new user : " + email)

			# generate confirm emain
			url = "/auth/confirm/" + generate_uuid()

			confirm = models.Confirm(email=email, type=models.Confirm_type.CONFIRM_REGISTER.name, url=url)
			db_session.add(confirm)
			db_session.commit()

			mail.make_confirm_email(email, url)

			return Response.ok()

		except Exception as e:
			current_app.logger.error(str(e))
			return Response.error(error_code.Global.UNKOWN)
コード例 #14
0
ファイル: sensor_hub.py プロジェクト: jdupl/iot
def add_record():
    try:
        lines = request.data.decode('utf-8').split('\n')
        secret = lines[0]
        if secret != app.config['IOT_SECRET']:
            return __forbidden()

        del lines[0:1]

        for timestamp_line in lines:
            pieces = timestamp_line.split(',')
            if len(pieces) < 2:
                return __bad_request()

            timestamp = pieces[0]
            arduino_uuid = pieces[1]  # TODO: Add to DB

            for piece in pieces[2:]:
                obj = extract_object_from_arduino_piece(piece, timestamp,
                                                        arduino_uuid)
                if obj:
                    db_session.add(obj)

        db_session.commit()
        return 'ok', 200
    except Exception as e:
        print(e)
        return __bad_request()
コード例 #15
0
ファイル: api.py プロジェクト: camerongray1515/HackDee-2015
def add_video():
    playlist_id = request.form.get("playlist_id")
    if playlist_id.strip() == "":
        return jsonify({'error': "You must specify a playlist ID for this video."})

    playlist = Playlist.query.get(playlist_id)
    if playlist == None:
        return jsonify({'error': "Playlist not found"})

    slug = request.form.get("slug")
    if slug.strip() == "":
        return jsonify({'error': "You must specify a slug for this video."})

    thumbnail_url = request.form.get("thumbnail_url")
    if thumbnail_url.strip() == "":
        return jsonify({'error': "You must specify a thumbnail for this video."})

    title = request.form.get("title")
    if title.strip() == "":
        return jsonify({'error': "You must specify a title for this video."})

    v = Video(playlist_id, slug, thumbnail_url, title)
    db_session.add(v)
    db_session.commit()    

    # Publish to Redis so that all clients update playlist
    data = {
        "action": "update_playlist",
        "playlist": Playlist.get_videos(playlist_id)
    }

    redis.publish(playlist_id, json.dumps(data))

    return jsonify({"success": True})
コード例 #16
0
def create_company():
    company = Company()
    company_data = json.loads(request.data)
    update_company_data(company, company_data)
    db_session.add(company)
    db_session.commit()
    return jsonify(company.to_dict())
コード例 #17
0
ファイル: unittest.py プロジェクト: bsdfzzzy/lehuo
def init_user_act():
	for i in range(10):
		usr = User(email='email#'+str(i), username='user#'+str(i), password=str(i))
		acti = Activity(content='act#'+str(i))
		db_session.add(usr)
		db_session.add(acti)
	db_session.commit()
コード例 #18
0
ファイル: rollchan.py プロジェクト: james-kelly/rollchan
def upload_file(board, post_id=None):
    # Create the post
    post = models.Post(subject=request.form.get('subject'),
                       comment=request.form.get('comment'),
                       parent_id=post_id)
    db_session.add(post)
    db_session.flush()

    # Upload the file if present
    f = request.files['file']

    if f.filename:
        extension = get_extension(f)
        filename = "{0}.{1}".format(post.generate_filename(), extension)
        path = "{0}/static/{1}".format(app.root_path, filename)

        f.save(path)

        post.filename = filename
        post.mimetype = f.mimetype

    db_session.commit()

    # Redirect to page or post
    if post_id:
        return redirect(url_for('reply', board=board, post_id=post_id))
    else:
        return redirect(url_for('page', board=board))
コード例 #19
0
ファイル: library.py プロジェクト: DimaWittmann/library
def author(aID):
    form = UpdateAuthorForm(request.form)
    selected_author = Author.query.filter(Author.id == aID).one()
    books = Book.query.all()
    form.books.choices = [(i, books[i - 1]) for i in xrange(1, len(books) + 1)]
    if request.method == 'GET':
        books = selected_author.books
        return render_template("author.html", books=books,\
               author=selected_author, form=form)
    elif request.method == 'POST' and form.validate():
        selected_author.name = form.new_name.data
        books = request.form.getlist('books')
        books = Book.query.filter(Book.id.in_(books)).all()
        for book in books:
            if book in selected_author.books:
                selected_author.books.remove(book)
            else:
                selected_author.books.append(book)
        db_session.commit()
        return redirect(url_for("author", aID=aID))
    elif request.method == 'DELETE':
        flash('{author} is deleted'.format(author=selected_author.name))
        db_session.delete(selected_author)
        db_session.commit()
        return url_for('index')
コード例 #20
0
ファイル: real_model.py プロジェクト: LichuanLu/redberry
    def test_addAllRole(self):
        from DoctorSpring.models.user import Role,UserRole
        role=Role()
        role.id=1
        role.roleName='fenzhen'
        session.add(role)

        role=Role()
        role.id=2
        role.roleName='doctor'
        session.add(role)

        role=Role()
        role.id=3
        role.roleName='patient'
        session.add(role)

        role=Role()
        role.id=4
        role.roleName='hospitalUser'
        session.add(role)

        role=Role()
        role.id=6
        role.roleName='kefu'
        session.add(role)



        session.commit()
        session.flush()
コード例 #21
0
ファイル: jokedbapp.py プロジェクト: BL-Labs/jokedbapp
def _update_and_store_transcription_metadata(t, request):
    if request.values.get("biblio_id", ""):
      try:
        biblio_id = int(request.values.get("biblio_id"))
        b = Biblio.query.get(biblio_id)
        if b:
          t.biblio = b
      except ValueError as e:
        pass

    user_id = session['logged_in_user']
    u = User.query.get(user_id)

    raw = request.values.get("raw", "")
    if raw:
      t.raw = raw
    text = request.values.get("text", "")
    if text:
      t.text = text

    t.edited = u
    t.pagestart = request.values.get("pagestart", "0")
    t.pageend = request.values.get("pagestart", "0")
    t.volume = request.values.get("volume", "")[:29]
    t.article_title = request.values.get("article_title", "")[:69]

    db_session.add(t)
    db_session.commit()
コード例 #22
0
ファイル: app.py プロジェクト: dariomadi/OpenExchange
def register():
    if request.method == 'POST':
        if "" in request.form.values():
            return render_template("register.html")
        if request.form['username'] in list(User.query.values(User.name)):
            return render_template("register.html",error="Please enter a password.")
        if request.form['email'] in list(User.query.values(User.email)):
            return render_template("register.html",error="Please enter a valid email.")
        if request.form['password'] != request.form['passwordconfirm']:
            return render_template("register.html",error="Passwords do not match.")
        #TODO: error for when they try to register when logged in already
        u = User(request.form['username'], request.form['email'],generate_password_hash(request.form['password'].strip()))
        db_session.add(u)
        db_session.commit()

        for currency in config.get_currencies():
            addr = generate_deposit_address(currency)
            a = Address(currency,addr,u.id)
            db_session.add(a)
        db_session.commit()
        if not send_confirm_email(u.id):
            return home_page("ltc_btc", danger='An error occured during registration. Please contact the administrator.')
        return home_page("ltc_btc", dismissable='Successfully registered. Please check your email and confirm your account before logging in.')

    if request.method == 'GET':
        return render_template("register.html")
コード例 #23
0
ファイル: views.py プロジェクト: gluker/jaot
def checkProblem(problem_id):
    problem = db_session.query(Problem).get(problem_id)
    form = request.form
    messages = []
    total = len(problem.requirements)
    correct = 0.0
    for req in problem.requirements:
        cond = req.condition
        try:
            if check_answer(cond,form):
                correct += 1
            else:
                messages.append(req.comment)
        except:
                return jsonify(errors = ["Please check the input!"])
    rate = int((correct/total)*100) if total != 0 else 100
    need_new = True
    for up in current_user.problems:
        if up.problem == problem:
            up.rate = rate
            need_new = False
            uproblem = up
            break
    if need_new:
        uproblem = UserProblem(rate=rate)
        uproblem.problem = problem
        current_user.problems.append(uproblem)
    trial = Trial()
    trial.rate = rate
    for key in request.form.keys():
        trial.answers.append(Answer(field=key,value=request.form[key]))
    uproblem.trials.append(trial)
    db_session.commit()
    return jsonify(messages = messages,rate = rate)
コード例 #24
0
ファイル: controller.py プロジェクト: 341-catan/catan
def build_road(player, vertex1, vertex2):
    if vertex2 < vertex1:
        (vertex1, vertex2) = (vertex2, vertex1)
    
    if (
        #the player has the resources
        player.hasResourcesFor(BuildTypes.ROAD) and

        #both vertices are valid
        v.isvalid(v.decompress(vertex1)) and
        v.isvalid(v.decompress(vertex2)) and

        #no other roads overlap
        Road.overlaps_q(player, vertex1, vertex2).count() == 0 and

        #the player has a road at one of the vertices already
        player.road_meets_q(vertex1, vertex2).count() != 0
    ) :

        player.takeResourcesFor(BuildTypes.ROAD)
        r = Road(player.UserID, vertex1, vertex2)
        player.game.roads.append(r)
        player.game.log(Log.road_built(player, r))

        # TODO: check if we now have longest road.
        # It is a longest path problem.  Check the rules before implementing

        db_session.commit()

        return "success"
    else:
        return "failure"
コード例 #25
0
 def setDiagnoseUploaded(cls,diagnoseId):
     if diagnoseId :
         diagnose=session.query(Diagnose).filter(Diagnose.id==diagnoseId,Diagnose.status!=DiagnoseStatus.Del).first()
         if diagnose:
             diagnose.ossUploaded=constant.DiagnoseUploaed.Uploaded
             session.commit()
             session.flush()
コード例 #26
0
ファイル: controller.py プロジェクト: 341-catan/catan
def join_game(game, user):
    if (
        #the game hasn't started yet
        game.State == Game.States.NOTSTARTED and

        #the user isn't already in the game
        GamePlayer.query. \
            filter_by(GameID=game.GameID). \
            filter_by(UserID=user.UserID). \
            count() == 0 and

        #there aren't already four players
        len(game.players) < 4
    ):
        player = user.join_game(game)

        #the game automatically starts when four players have joined
        if len(game.players) == 4:
            game.start()
            log_state_change(game)

        db_session.commit()
        return player
    else:
        return None
コード例 #27
0
ファイル: app.py プロジェクト: ribbskott/SwimCoachAPI
def club_pictures(rowkey):
    if not check_auth(request):
        abort(403)
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return make_response('No file part', 400)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            return make_response('No file part', 400)
        if not allowed_file(file.filename):
            return make_response('The filetype is not allowed')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filename = rowkey + "." + filename.rsplit('.', 1)[1]
            file.save(os.path.join(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], filename))
            db_picture = db_session.query(UserFile).filter_by(owner=rowkey, file_type='ProfilePicture')
            if len(list(db_picture)) == 0:
                db_picture = UserFile()
                db_picture.file_type = 'ProfilePicture'
                db_picture.owner = rowkey
                db_session.add(db_picture)
                db_session.commit()
                return make_response("",200)
            db_picture.update({"file_name":filename})
            db_session.commit()
            return make_response("", 200)
    if request.method == 'GET':
        filename = db_session.query(UserFile).filter_by(file_type='ProfilePicture', owner=rowkey)[0].file_name
        return jsonify({"filename":  str.replace(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], "static\\Sloach\\", "") + "/" + filename})
コード例 #28
0
ファイル: controller.py プロジェクト: 341-catan/catan
def build_settlement(player, p):
    #TODO: make sure decompress checks validity
    vertex = v.decompress(p)

    if (
        players_turn(player) and

        #there are no settlements within the distance rule
        Settlement.distance_rule(player.GameID, vertex) and

        #and the player has a road to the vertex
        player.roads_q().count() > 0 and #FIXME

        #and the player has the requisite resources
        player.hasResourcesFor(BuildTypes.TOWN)
    ) :
        player.takeResourcesFor(BuildTypes.TOWN)
        #Actually, I think it would be better to just have add_settlement written here inline
        s = player.add_settlement(p)
        player.Score += 1
        player.game.log(Log.settlement_built(player, s))
        player.checkVictory()


        db_session.commit()

        return "success"
    else:
        return "failure"
コード例 #29
0
ファイル: app.py プロジェクト: ribbskott/SwimCoachAPI
def get_club(rowkey):
    if not check_auth(request):
        abort(403)
    club = db_session.query(Club).filter_by(rowkey=rowkey).first()
    if club is None:
        abort(404)
    if request.method =='GET':
        return jsonify({'idclub': club.idclub, 'name': club.name, 'description': club.description,
                        'postaladdress': club.postaladdress,
                        'postalzipcode': club.postalzipcode,
                        'postalcity': club.postalcity,
                        'visitingaddress': club.visitingaddress,
                        'visitingzipcode': club.visitingzipcode,
                        'visitingcity': club.visitingcity,
                        'rowkey': club.rowkey})

    if request.method =='POST':
        club.visitingaddress = request.json["visitingaddress"]
        club.visitingzipcode = request.json["visitingzipcode"]
        club.visitingcity = request.json["visitingcity"]
        club.name = request.json["name"]
        club.postaladdress = request.json["postaladdress"]
        club.postalzipcode = request.json["postalzipcode"]
        club.postalcity = request.json["postalcity"]
        db_session.commit()

    return jsonify({'idclub': club.idclub, 'name': club.name, 'description': club.description,
                        'postaladdress': club.postaladdress,
                        'postalzipcode': club.postalzipcode,
                        'postalcity': club.postalcity,
                        'visitingaddress': club.visitingaddress,
                        'visitingzipcode': club.visitingzipcode,
                        'visitingcity': club.visitingcity,
                        'rowkey': club.rowkey})
コード例 #30
0
ファイル: hello.py プロジェクト: 72L/72L.github.io
def database():

	#check if user is in database
	if ( User.query.filter(User.email == request.form['email']).count() > 0):
		return "already recorded"

	#else, new user
	us = User(request.form['fullname'], request.form['email'])
	db_session.add(us)
	db_session.commit()

	#Get Message
	subject = 'Welcome to Papaya'
	message = "Hello "+ request.form['givenname'] + "!\n\n We're so glad you signed up for our alpha service. This is the humble start of an incredibly simple way to make your calendar data useful, so you can learn about and adapt to how you spend time. Over the course of the coming year, we will be rolling out a series of amazing features and will periodically keep you updated. \n\n Carpe Diem!\n- Papaya Team \n\n"
	name = request.form['fullname']
	address = request.form['email']

	#sent email
	requests.post(
		"https://api.mailgun.net/v2/sandbox371c5172c8984738b35884a88e2fc92b.mailgun.org/messages",
		auth=("api", "key-b90954e35d130bce6ed45af6fe5b795a"),
		data={"from": "Papaya App <[email protected]>",
					"to": name+" <"+address+">",
					"subject": subject,
					"text": message})

	return 'Welcome Email Sent'