Beispiel #1
0
    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
Beispiel #2
0
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})
Beispiel #3
0
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()
Beispiel #4
0
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))
Beispiel #5
0
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()
Beispiel #6
0
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')
Beispiel #7
0
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'
    )
Beispiel #8
0
def init_user_act():
	for i in range(10):
		usr = User(email='email#'+str(i), username='******'+str(i), password=str(i))
		acti = Activity(content='act#'+str(i))
		db_session.add(usr)
		db_session.add(acti)
	db_session.commit()
Beispiel #9
0
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')
Beispiel #10
0
	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 : "******"/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)
Beispiel #11
0
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})
Beispiel #12
0
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
Beispiel #13
0
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"
Beispiel #14
0
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)
Beispiel #15
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()
Beispiel #16
0
 def changeDiagnoseStatus(cls,diagnoseId,status):
     if diagnoseId and status:
         diagnose=Diagnose.getDiagnoseById(diagnoseId)
         if diagnose:
             diagnose.status=status
             session.commit()
             session.flush()
Beispiel #17
0
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"})
Beispiel #18
0
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"
Beispiel #19
0
    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()
Beispiel #20
0
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)
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())
Beispiel #22
0
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))
Beispiel #23
0
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)
Beispiel #24
0
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)
Beispiel #25
0
	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)
Beispiel #26
0
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', )
Beispiel #27
0
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")
Beispiel #28
0
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})
Beispiel #29
0
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
Beispiel #30
0
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 <*****@*****.**>",
					"to": name+" <"+address+">",
					"subject": subject,
					"text": message})

	return 'Welcome Email Sent'
Beispiel #31
0
def start_semi_final(tournament, games):
    semi_finalists = []
    for game in games:
        game_details = db_session.query(gameDetails).filter_by(
            game_id=game.id).first()
        if game_details.winner != None:
            if type(game_details.winner) is float:
                semi_finalists.append(int(abs(game_details.winner) / 1.11))
            else:
                semi_finalists.append(abs(game_details.winner))

    if len(semi_finalists) < 4:
        tournament.semi_final = ""
        db_session.commit()
        return abort(409)

    tournament.semi_final = str(semi_finalists)
    db_session.commit()

    for i in range(0, 4, 2):
        game_id = get_random_string(7)
        player_one = db_session.query(User).filter_by(
            id=semi_finalists[i]).first()
        player_two = db_session.query(User).filter_by(
            id=semi_finalists[i + 1]).first()
        gameT = GameT(game_id, player_one.id, player_two.id, tournament.id)
        db_session.add(gameT)
        game_details = gameDetails(game_id)
        db_session.add(game_details)

    db_session.commit()
    return "OK"
Beispiel #32
0
def upload_picture(recipe_id):
    """Upload and associate image with a recipe"""
    # Check if the token is correct to prevent CSRF
    if request.headers.get('italian-recipes-token') != login_session['state']:
        resp = jsonify(error=['You are not allowed to make such request.'])
        resp.status_code = 401
        return resp

    # Check if user is logged in
    if 'username' not in login_session:
        resp = jsonify(error=['You are not allowed to do this'])
        resp.status_code = 401
        return resp

    recipe = db_session.query(Recipe).filter_by(id=recipe_id).one()

    # Check if current user is the recipe's owner
    if recipe.user_id != login_session['user_id']:
        resp = jsonify(error=['You are not authorized to do this!'])
        resp.status_code = 403
        return resp

    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = str(recipe.id) + '-' + secure_filename(file.filename)
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        # Let's remove the old image if any were assiociated to the recipe
        if (recipe.image_url is not None):
            removeImage(recipe.image_url)
        recipe.image_url = filename
        db_session.add(recipe)
        db_session.commit()
        return jsonify(collection=[recipe.serialize])
    else:
        errorMsg = """It \'s likely that 
        you sent an invalid format file. 
        Could not process your request."""
        resp = jsonify(error=[errorMsg])
        resp.status_code = 400
        return resp
Beispiel #33
0
def relation2mysql(time_dir):
    file_path = csv_dir + "relation/%s/relation.csv" % (time_dir)
    f = open(file_path, "r")
    data = csv.reader(f)
    nrows = 0
    relationList = []
    print u"----> 开始存储关系数据..."
    cnt_suc = 0
    for row in data:
        nrows += 1
        #print len(row)
        #print "%s / %s " % (row[0], row[1])
        try:
            pdf_path = str(row[0].strip())
            pdf_page = int(row[1].strip())
            mark_id = int(row[2].strip())
            statement = db_session.query(VerStatement).filter(
                VerStatement.pdf_path == pdf_path,
                VerStatement.pdf_no == pdf_page,
                VerStatement.mark_id == mark_id).first()
            if statement == None:
                print "pdf_path=%s, pdf_page=%d, mark_id=%d" % (
                    pdf_path, pdf_page, mark_id)
            assert (statement != None)  # 必须存在对应的entity

            stat_id = statement.id
            relation_no = row[5].strip()
            relation_no = int(relation_no)
            content = "".join([seg.strip() for seg in row[6:]])

            newRelation = RelationMark(content, relation_no, stat_id)
            relationList.append(newRelation)
            cnt_suc += 1
        except:
            print u"数据行%d 存在异常" % nrows
            print traceback.format_exc()
    db_session.add_all(relationList)
    db_session.commit()
    del relationList[:]
    print u"----> 关系数据存储完毕,总共存储数据%d行,数据异常共%d行" % (cnt_suc, nrows - cnt_suc)
Beispiel #34
0
def transaction(uuid=None):
    if request.method == 'GET':
        if uuid is None:
            abort(404)

        transaction = models.Transaction.query.get(uuid)
        if not transaction:
            abort(404)
        return render_template('transaction.html', transaction=transaction)

    elif request.method == "PATCH":
        if not request.args.get(
                "APIKEY") == 'a3e419378b514f2db99c4d00a1a5fcd9':
            return jsonify({"error": "Incorrect APIKEY"})

        if uuid is None:
            return jsonify({"error": "UUID Not Found"})

        transaction = models.Transaction.query.get(uuid)
        if not transaction:
            return jsonify({"error": "No Transaction Found"})

        if not request.mimetype == 'application/json':
            return jsonify({"error": "Incorrect Content-Type"})

        if request.get_json():
            updateData = request.get_json()
        else:
            return jsonify({"error": "Invalid Payload"})

        signatures = []

        if 'signatures' in updateData:
            for signature in updateData['signatures']:
                signatures.append(models.TransactionSignature(signature))

        transaction.signatures = signatures
        db_session.commit()

        return jsonify({'sucess': True})
Beispiel #35
0
def key():
    user = current_user._get_current_object()
    keys = Keys.query.all()
    error = ''
    generated = 'false'
    if request.method == 'GET':
        keyform = keyForm()
        return render_template('key.html',
                               user=user,
                               keys=keys,
                               keyform=keyform,
                               generated=generated)
    else:
        keyform = keyForm(request.form)
        if keyform.date.data > date.today():
            error = ""
            key = Keys()
            key.expiration = keyform.date.data
            key.token = token_hex(16)
            key.description = keyform.description.data
            response = urlopen("http://tinyurl.com/api-create.php?url=" +
                               urlsurvey + key.token)
            key.urlsurvey = response.read().decode('utf-8')
            response2 = urlopen("http://tinyurl.com/api-create.php?url=" +
                                urledu + key.token)
            key.urledu = response2.read().decode('utf-8')

            user_datastore.put(key)
            db_session.commit()
            generated = key.token
            keyform = keyForm()
        else:
            error = "Data inserita non valida, validità minima: 1 giorno"
        keys = Keys.query.all()
        return render_template('key.html',
                               user=user,
                               keys=keys,
                               keyform=keyform,
                               error=error,
                               generated=generated)
def login():
    if request.method == 'POST':
        if not request.json:
            abort(400)

        login = request.json.get('login')
        password = request.json.get('password')

        errors = []

        if login is None or login == '':
            errors.append('Login is required')

        if password is None or password == '':
            errors.append('Password is required')

        if len(errors) is not 0:
            abort(422, {'errors': errors})

        u = User.query.filter(User.login == login).first()

        if not u or not u.verify_password(password):
            abort(422, {'error': 'Wrong login or password'})

        u.last_logged_in = datetime.now()

        db_session.add(u)
        db_session.commit()
        #TODO: add proper group handling
        #		role = Role.query.filter(Role.ID == u.role_id).first()

        result = {
            'first_name': u.first_name,
            'last_name': u.last_name,
            'email': u.email,
            #			'role': role.name,
            'auth_token': generate_auth_token(u)
        }

        return Response(ujson.dumps(result), mimetype='application/json')
Beispiel #37
0
    def add_job(self, job, position=-1):
        """Add a job to the printer. This will set it to the position.
        If another job is in that location, it bumps it back. Cannot add 
        to front of queue
        :job: Adds job to the the printer queue
        :position: Position to be added to the queue. If -1, appends
        :returns: Boolean of success

        """
        if position == 0:
            return False
        for j in self.jobs:
            if j.id == job.id:
                return False
        if position == -1:
            job.state("queued")
            self.jobs.append(job)
            db_session.commit()
            return True
        if position >= len(self.jobs):
            job.state("queued")
            self.jobs.append(job)
            db_session.commit()
            return True
        else:
            job.state("queued")
            self.jobs.insert(position, job)
            db_session.commit()
            return True
Beispiel #38
0
def _add_repository(url):
    identity_file = current_user.generated_identity_file

    if identity_file is None:
        return UnifiedResponse(
            result='fail',
            details="Current user doesn't have generated identity file"
        )

    validation = validate_repository(url, identity_file, current_user.email)

    if validation.result == 'ok':
        repo = Repository(user_id=current_user.id,
                          url=url,
                          identity_file=identity_file)
        try:
            db_session.add(repo)
            current_user.active_repository_id = repo.id
            current_user.generated_identity_file = None
            db_session.commit()
            response = UnifiedResponse(
                result='ok',
                details=''
            )
        except SQLAlchemyError:
            db_session.rollback()
            response = UnifiedResponse(
                result='fail',
                details='Failed to save the repository into database'
            )
    else:
        response = UnifiedResponse(
            result='fail',
            details=['Failed to validate the url:'] + process_details(validation.details)
        )

    response.update(dict(
        repositories=user_repositories(current_user)
    ))
    return response
Beispiel #39
0
def create_class(*args, **kwargs):
    role = kwargs['role']

    data = dict()
    if request.is_json:
        data = request.get_json()
    else:
        return jsonify({
            "status": 0,
            "message": "invalid format json type"
        }), 400

    if role != 2:
        return jsonify({
            "status": 0,
            "message": "Only teacher can create class!"
        }), 400
    data['tutor_id'] = kwargs['user_id']
    schema = ClassSchema()
    result = validate_schema(schema, data)

    if bool(result.errors):
        result.errors['status'] = 0
        return jsonify(result.errors), 400

    new_class = Class.register_new_class(data['name'], data['student_limit'],
                                         data['tutor_id'])

    try:
        session.add(new_class)
        session.commit()
        pass
    except IntegrityError as e:
        return jsonify({"status": 0, "message": "cannot create class!"}), 400

    return jsonify({
        'status': 1,
        'message': "new Class created",
        'data': schema.dump(new_class)
    }), 200
Beispiel #40
0
def new_planning():
    user_id = g.user_id
    planning_id = _generate_planning_uuid()
    folder = os.path.join(app.config['UPLOAD_FOLDER'], planning_id)
    if os.path.isdir(folder):
        raise Exception('Planning uuid collision. UUID4 busted ?')
    os.makedirs(folder)

    # Get ICS
    if 'ics_url' in request.form:
        try:
            ics_url = request.form['ics_url']
            ics_fullpath = _dl_and_save_ics_file(ics_url, folder)
        except CAPException as e:
            return e.res
    elif 'ics_file' in request.files:
        ics_file = request.files['ics_file']
        ics_fullpath = _save_ics_file(ics_file, folder)
    else:
        return _bad_request()

    # Get MBZ or empty mbz_fullpath
    mbz_fullpath = None
    if 'mbz_file' in request.files:
        mbz_file = request.files['mbz_file']
        mbz_fullpath = _save_mbz_file(mbz_file, folder)

    # .get() returns None if key is not defined
    # Client should be pressured to send the information from the front-end
    name = request.form.get('name')
    year = request.form.get('year')
    semester = request.form.get('semester')
    group = request.form.get('group')

    planning = Planning(planning_id, user_id, '', ics_fullpath, mbz_fullpath,
                        name, year, semester, group)
    db_session.add(planning)
    db_session.commit()

    return jsonify(planning=planning.as_pub_dict())
def ingest2db(df_, fsc, params, run_id, model_name):

    # Add metadata object to DB
    meta = Metadata(
        run_id=run_id,
        model=model_name,
        raw_output_link=
        f"https://model-service.worldmodelers.com/results/{model_name}_results/{run_id}.csv",
        run_label=f"{model_name} run for {params['shocked_region']} region.",
        point_resolution_meters=100000)
    db_session.add(meta)
    db_session.commit()

    # Add parameters to DB
    for pp, vv in params.items():
        param = Parameters(run_id=run_id,
                           model=model_name,
                           parameter_name=pp,
                           parameter_value=vv,
                           parameter_type="string")
        db_session.add(param)
        db_session.commit()

    # Ingest outputs to DB
    feature_name = fsc['outputs'][0]['name']
    feature_description = fsc['outputs'][0]['description']
    df_['datetime'] = datetime(year=2018, month=1, day=1)
    df_['run_id'] = run_id
    df_['model'] = model_name
    df_['feature_name'] = feature_name
    df_['feature_description'] = feature_description
    df_['feature_value'] = df_[feature_name].apply(lambda x: int(x))

    db_session.bulk_insert_mappings(Output, df_.to_dict(orient="records"))
    db_session.commit()
def ingest_to_db(InRaster, run_id, *,
                model_name, start, included_months, total_months,
                params, basin):

    # Add metadata object to DB
    meta = Metadata(run_id=run_id, 
                    model=model_name,
                    raw_output_link= f"https://model-service.worldmodelers.com/results/PIHM_results/{run_id}.tif",
                    run_label=f"{model_name} run for {basin} Basin.",
                    point_resolution_meters=200)
    db_session.add(meta)
    db_session.commit()

    # Add parameters to DB
    print("Storing parameters...")
    for pp, vv in params.items():

        if pp == 'basin':
            p_type = 'string'
        else:
            p_type = 'float'
            
        param = Parameters(run_id=run_id,
                          model=model_name,
                          parameter_name=pp,
                          parameter_value=vv,
                          parameter_type=p_type
                          )
        db_session.add(param)
        db_session.commit()        
        
    # iterate over the bands that should be included (1 per month)
    for month in range(1, included_months + 2):
        date_ = start + relativedelta(months=month-1)
        date_str = date_.strftime("%m/%d/%Y")        
        print(f"Processing {model_name} {date_str}")
        # Convert Raster to GeoPandas
        feature_name = m['outputs'][0]['name']
        feature_description = m['outputs'][0]['description']
        gdf = raster2gpd(InRaster,feature_name,band=month)

        print(f"Performing spatial merge")
        # Spatial merge on GADM to obtain admin areas
        gdf = gpd.sjoin(gdf, admin2, how="left", op='intersects')
        
        # Iterate over years for each band to ensure that there is continous
        # annual data
        # Set run fields: datetime, run_id, model
        gdf['datetime'] = date_
        gdf['run_id'] = run_id
        gdf['model'] = model_name
        gdf['feature_description'] = feature_description
        if 'geometry' in gdf:
            del(gdf['geometry'])
            del(gdf['index_right'])

        # perform bulk insert of entire geopandas DF
        print(f"Ingesting {date_str} of {model_name} for basin {basin} to database\n")
        db_session.bulk_insert_mappings(Output, gdf.to_dict(orient="records"))
        db_session.commit()    
Beispiel #43
0
def sync_database_online(url):
    while True:
        lastupdateall = logger.query.all()
        if len(lastupdateall):
            lastupdate = lastupdateall[0].lastupdate
        else:
            lastupdate = None
        try:
            
            if not lastupdate:
                logs = CameraInfo.query.all()
            else:
                logs = CameraInfo.query.filter(CameraInfo.timestamp >= lastupdate).all()
    
            for obj in logs:
                data = {"face":obj.face,"camera":obj.camera_name,"timestamp":obj.timestamp,"service":obj.service}
                requests.post(url,data=data)
            
            print("-"*40)
            print("[master][sync_database_online] Data is sent for sycning online Database with local database")
            print("-"*40)
            
            newTime = datetime.datetime.now()

            if not lastupdate:
                l = logger(lastupdate=newTime)
                db_session.add(l)
                db_session.commit()
            else:
                l = logger.query.all()[0]
                l.lastupdate = newTime
                db_session.commit()
                
        except Exception as e:
            print("-"*40)
            print("[master][sync_database_online]",e)
            print("[master][sync_database_online] Not able to update online database, may be system not connect to internet or any other issue in sync_database_online function")
            print("-"*40)
        finally:
            time.sleep(60)
Beispiel #44
0
 def index(self):
     if   request.method=='GET':
         form = IpInfoForm()
         message="""
         please input ip and  choice:
         """
         return self.render('myIndex.html',message=message,form=form)
     else:
         ip=request.form['ip']
         para_tp=request.form['choice']
         form = IpInfoForm(request.form)
         if   form.validate() and   para_tp in sql_results.keys():
             if  int(para_tp)<4:
                 md5_ip =self.ip_md5(ip+'Anonymous')
                 ip_obj=IPINFO.query.filter_by(ip_log=md5_ip).first()
                 if  ip_obj:
                     #这里不存在就不去添加了 --人为改,不判断是否白名单
                     ip_obj.unlock_times+=1
                     (ip_obj.lock_1m_times,ip_obj.lock_30m_times,ip_obj.lock_status,
                     ip_obj.white_list_status,unlock_after_lockd)=sql_results[para_tp]
             else:
                 #封ip段不管有没有用户名
                 ipseg_list=ip.split('.')
                 ipseg_list.pop()
                 ip_str='.'.join(ipseg_list)
                 md5_ip=self.ip_md5(ip_str)
                 ip_obj=IPSEG.query.filter_by(ipseg=md5_ip).first()
                 if  not ip_obj:
                     ip_obj=IPSEG(ip_str,md5_ip)
                     db_session.add(ip_obj)
                     db_session.commit()
                 ip_obj.ipseg_status=sql_results[para_tp]
             db_session.commit()
             message='ip  %s changed to status %s' %(ip,para_tp)
             flash('update success')
             return  self.render('myIndex.html',message=message,form=form)
         else:
             flash('ip or choice wrong')
             message = 'please try again'
             return self.render('myIndex.html', message=message, form=form)
def do_compiler(compiler):
    version_sha = get_latest_remote_version(compiler.repo_url)
    compiler.last_check_time = datetime.utcnow()
    db_session.commit()
    if not version_sha:
        return
    newer = False
    if compiler.latest_version_id:
        version = db_session.query(Version)\
                            .filter(Version.id == compiler.latest_version_id)\
                            .one()
        if version_sha != version.sha:
            newer = True
    else:
        newer = True
    if newer:
        print "add %s's version %s" % (compiler.student, version_sha)
        version = Version(compiler_id=compiler.id,
                          sha=version_sha,
                          phase='build',
                          status='pending')
        db_session.add(version)
        db_session.commit()
        compiler.latest_version_id = version.id
        db_session.commit()
Beispiel #46
0
def change():
    form = ChangePasswordForm()

    if request.method == "GET":
        return render_template("change.html", form=form)

    elif request.method == "POST":
        oldPass = form.oldpassword.data
        newPass = form.newpassword.data
        newPassReType = form.newpasswordretype.data
        if form.validate_on_submit():
            # Return error if no input is received
            if oldPass is None or newPass is None or newPassReType is None:
                return render_template("change.html",
                                       form=form,
                                       message="Invalid Input")

            # Return error if oldPass dosen't match DB pass
            if not current_user.password == oldPass:
                return render_template("change.html",
                                       form=form,
                                       message="Incorrect Password")

            # Return error if newPass and newPassReType dosen't match
            if not newPass == newPassReType:
                return render_template(
                    "change.html",
                    form=form,
                    message="Incorrect Input: Passwords not matching")

            current_user.password = newPass
            db_session.commit()
            return render_template("change.html",
                                   form=form,
                                   message="Password Changed")

        else:
            return render_template("change.html",
                                   form=form,
                                   message="Invalid Input")
Beispiel #47
0
def addServerToRack():
    '''
    Добавление сервера в стойку
    :param server_id: id of server
    :param rack_id: id of rack
    :return:
    '''

    if not request.json or not request.json['server_id'] or not request.json[
            'rack_id']:
        return getMessage('Error: not enough arguments')

    server_id = request.json['server_id']
    rack_id = request.json['rack_id']
    server = Server.query.filter(Server.id == server_id).first()
    rack = Rack.query.filter(Rack.id == rack_id).first()

    if not server:
        return getMessage('Error: server with id %s not found' % server_id)
    elif not rack:
        return getMessage('Error: rack with id %s not found' % rack_id)
    elif not server.getStatus() in ['Unpaid', 'Deleted', 'Without status']:
        return getMessage('Error: cannot use server in status %s' %
                          server.getStatus())
    elif server.rack_id:
        return getMessage('Error: server already in rack with id %s' %
                          server.rack_id)
    elif rack.getSize() == rack.getBuzySlots():
        return getMessage('Error: rack is full')

    try:
        server.status_id = RbStatus.query.filter(
            RbStatus.value == 'Unpaid').first().id
        server.rack_id = rack.id
        server.modifyDatetime = func.now()
        rack.modifyDatetime = func.now()
        db_session.commit()
        return getMessage('Server added to rack')
    except:
        return getMessage('Error adding server to rack')
Beispiel #48
0
def uppdateRecipe(recipe_id):
    """RESTful method for updating a recipe"""
    # Check if the token is correct to prevent CSRF
    if request.headers.get('italian-recipes-token') != login_session['state']:
        resp = jsonify(error=['You are not allowed to make such request.'])
        resp.status_code = 401
        return resp

    # Check if user is logged in
    if 'username' not in login_session:
        resp = jsonify(error=['You are not allowed to do this'])
        resp.status_code = 401
        return resp

    recipe = db_session.query(Recipe).filter_by(id=recipe_id).one()

    # Check if current user is the recipe's owner
    if recipe.user_id != login_session['user_id']:
        resp = jsonify(error=['You are not authorized to do this!'])
        resp.status_code = 403
        return resp

    # Check if all require input fields were filled
    # Sanitize input data
    data = checkRecipeForm(request.get_json())
    # If no errors, we are good
    if (len(data.errors) == 0):
        recipe.name = data.inputs['name']
        recipe.description = data.inputs['description']
        recipe.duration = data.inputs['duration']
        recipe.difficulty = data.inputs['difficulty']
        recipe.region_id = data.inputs['region_id']
        recipe.last_update = func.now()
        db_session.add(recipe)
        db_session.commit()
        return jsonify(collection=[recipe.serialize])
    else:
        resp = jsonify(error=data.errors)
        resp.status_code = 400
        return resp
Beispiel #49
0
def request_action(token=None):
    req = KycRequest.from_token(db_session, token)
    if not req:
        return abort(404, 'sorry, request not found')
    # get user email from db
    email = ''
    user_req = UserRequest.from_request(db_session, req)
    if user_req:
        user = User.from_id(db_session, user_req.user_id)
        if user:
            email = user.email
    # process any posted data
    aplyid_transaction_id = None
    if req.aplyid:
        aplyid_transaction_id = req.aplyid.transaction_id
    verification_message = None
    if request.method == 'POST':
        aplyid_phone = request.form.get('aplyidPhone')
        if aplyid_phone:
            print("aplyid_phone: " + aplyid_phone)
            transaction_id = aplyid_send_text(aplyid_phone, req.token)
            if transaction_id:
                aplyid = AplyId(req, transaction_id)
                db_session.add(aplyid)
                db_session.commit()
                aplyid_transaction_id = transaction_id
            else:
                verification_message = 'unable to send text message, please ensure the mobile number is valid (country code first without the "+", followed by the phone number without any leading zeros "0")'
        # check ezpay verification
        ezpay_pass = request.form.get('ezpayPass')
        if ezpay_pass:
            result, verification_message = ezpay_get_verification_result(email, ezpay_pass)
            print(verification_message)
            if result:
                req.status = req.STATUS_COMPLETED
                db_session.add(req)
                db_session.commit()
                call_webhook(req)
    # render template
    return render_template('request.html', production=PRODUCTION, parent_site=PARENT_SITE, token=token, completed=req.status==req.STATUS_COMPLETED, email=email, aplyid_transaction_id=aplyid_transaction_id, verification_message=verification_message)
Beispiel #50
0
    def test_problem(self):
        """test the problem table"""
        # add problem type
        PROBLEM_TYPE_ARGS = {
            "name": "input/output",
            "eval_script": "#!/bin/bash\nexit 0",
        }
        problem_type = model.ProblemType(**PROBLEM_TYPE_ARGS)
        db_session.add(problem_type)
        db_session.commit()

        PROBLEM_ARGS = {
            "problem_type":
            problem_type,
            "slug":
            "ioprob",
            "name":
            "The Input/Output Problem",
            "problem_statement":
            "Print the string 'Hello, World!' n times",
            "sample_input":
            "3",
            "sample_output":
            "Hello, World!Hello, World!Hello, World!",
            "secret_input":
            "4",
            "secret_output":
            "Hello, World!Hello, World!Hello, World!Hello, World!",
        }

        # create and add contest
        problem = model.Problem(**PROBLEM_ARGS)
        db_session.add(problem)
        db_session.commit()

        # fetch contest
        results = model.Problem.query.filter_by(
            name=PROBLEM_ARGS["name"]).all()

        self.assertEqual(len(results), 1)
Beispiel #51
0
def vps_update():
    vps_id = request.form['idvpss'].strip()
    ip = request.form['ip'].strip()
    port = request.form['port'].strip()
    login = request.form['user'].strip()
    password = request.form['password']

    vps = VPS.query.filter(VPS.idvpss == vps_id).first()

    vps.ip = ip
    vps.port = port
    vps.login = login
    if password: vps.password = password
    db_session.add(vps)
    try:
        db_session.commit()
    except Exception as e:
        logging.error("Application did not update " + vps.__repr__() +
                      " becouse " + e.message)
        db_session.rollback()
        raise Exception('DB commit is not OK')
    return "UPDATED"
Beispiel #52
0
    def put(self, role_id):
        if check_member_role(["admin"], current_user.email) == False:
            return {
                "message": 'Missing authorization to retrieve content',
            }, 401

        if "application/json" in request.headers["Content-Type"]:
            description = request.json.get("description")
            label = request.json.get("label")
            render_structure = request.json.get("render_structure")

            role = Role.query.filter_by(id=role_id).first()
            if role:
                if description is not None:
                    role.description = description
                if label is not None:
                    role.label = label
                if render_structure is not None:
                    role.render_structure = render_structure
                db_session.commit()
                role_updated = Role.query.filter_by(id=role_id).first()
                return {
                    "version":
                    api_version,
                    "message":
                    "Update {}(id: {}) info".format(role_updated.label,
                                                    role_updated.id),
                    "data": {
                        "id": role_updated.id,
                        "description": role_updated.description,
                        "label": role_updated.label,
                        "render_structure": role_updated.render_structure
                    }
                }, 200
        return {
            "version": api_version,
            "message": "Check header and data type",
            "data": {}
        }, 404
Beispiel #53
0
def addDoctor():
    docJson = request.get_json()
    doctorDetails = Doctor(docJson['name'], 
        docJson['email'], 
        docJson['experience'],
        docJson['education'], 
        docJson['recommendations'])
    specList = docJson['speclist']
    clinicList = docJson['cliniclist']
    for specialityName in specList:
        speciality = Speciality.query.filter_by(name = specialityName['name']).first()
        doctorDetails.speciality.append(speciality)
    for clinicName in clinicList:
        clinic = Clinic.query.filter_by(name = clinicName['name']).first()
        doctorDetails.clinics.append(clinic)
    db_session.add(doctorDetails)
    try:
        db_session.commit()
    except SQLAlchemyError as exception:
        db_session.rollback()
    page = {'returnCode': "SUCCESS", 'data':{}, 'errorCode':None}
    return jsonify(page)
Beispiel #54
0
def add_company(corp_code=None,
                corp_name=None,
                corp_name_eng=None,
                stock_name=None,
                stock_code=None,
                ceo_nm=None,
                corp_cls=None,
                jurir_no=None,
                bizr_no=None,
                adres=None,
                hm_url=None,
                ir_url=None,
                phn_no=None,
                fax_no=None,
                induty_code=None,
                est_dt=None,
                acc_mt=None):
    c = Company(corp_code, corp_name, corp_name_eng, stock_name, stock_code,
                ceo_nm, corp_cls, jurir_no, bizr_no, adres, hm_url, ir_url,
                phn_no, fax_no, induty_code, est_dt, acc_mt)
    db_session.add(c)
    db_session.commit()
Beispiel #55
0
def editDoctor():
    doctorJson = request.get_json()
    print doctorJson
    db_session.query(Doctor).filter_by(id = doctorJson['id']).update({
        'name' : doctorJson['name'],
        'email' : doctorJson['email'], 
        'experience' : doctorJson['experience'],
        'education' : doctorJson['education'], 
        'recommendations' : doctorJson['recommendations']
    })
    specList = doctorJson['speclist']
    specDelete = DoctorsSpeciality.query.filter_by(doctorIdFK = doctorJson['id'])
    for specdel in specDelete:
        del specdel
        db_session.commit()
    docObj = Doctor.query.get(doctorJson['id'])
    for specialityName in specList:
        print specialityName['specName']
        speciality = Speciality.query.filter_by(name = specialityName['specName']).first()
        docObj.speciality.append(speciality)
        db_session.commit()


    clinicList = doctorJson['cliniclist']
    clinicDelete = DoctorsClinic.query.filter_by(doctorIdFK = doctorJson['id'])
    for clinicdel in clinicDelete:
        del clinicdel
        db_session.commit()
    for clinicName in clinicList:
        clinic = Clinic.query.filter_by(name = clinicName['clinicName']).first()
        docObj.clinics.append(clinic)
        db_session.commit()

    try:
        db_session.commit()
    except SQLAlchemyError as exception:
        db_session.rollback()
    page = {'returnCode': "SUCCESS", 'data':{}, 'errorCode':None}
    return jsonify(page)
Beispiel #56
0
def create_user():
    init_db()
    if not check_if_exists(Role, name='admin'):
        user_datastore.create_role(name='admin', description='Admin Role')

        user_datastore.create_role(name='user', description='User Role')
        db_session.commit()

    if not check_if_exists(User, email='*****@*****.**'):
        user = user_datastore.create_user(email='*****@*****.**',
                                          password='******',
                                          roles=['admin'])
        user_datastore.create_user(
            email='<script>console.log("testscript")</script>@gmail.com',
            password='******',
            roles=['user'])
        for fake_id in range(1, 50):
            user_datastore.create_user(
                email='user_1{}@gaml.com'.format(fake_id),
                password='******',
                roles=['user'])
        db_session.commit()
def remove_ava():
    theLock.acquire()
    # Fetching info from the calendar implemented in canvasser
    title = request.args.get('title')
    start = request.args.get('start')
    ############ Change Date string to Date object (yyyy-mm-dd)
    dateStrings = start.split()
    dateString = dateStrings[3] + " " + dateStrings[1] + " " + dateStrings[2]
    struc = time.strptime(dateString, '%Y %b %d')
    startDate = datetime.date(struc.tm_year, struc.tm_mon, struc.tm_mday)
    ''' Query Role Id firstly, the query CanAva obj'''
    role_obj = db_session.query(Role).filter(Role.email == user_email,
                                             Role.role == 'canvasser').first()
    ava_obj = db_session.query(CanAva).filter(
        CanAva.role_id == role_obj.id, CanAva.theDate == startDate).first()
    db_session.delete(ava_obj)
    db_session.commit()

    logging.info("delete available date for email " + user_email + " with " +
                 " the date on " + start)
    theLock.release()
    return 'remove'
def update_ava():
    theLock.acquire()
    # Fetching info from the calendar implemented in canvasser
    title = request.args.get('title')
    start = request.args.get('start')
    ############ Change Date string to Date object (yyyy-mm-dd)
    dateStrings = start.split()
    dateString = dateStrings[3] + " " + dateStrings[1] + " " + dateStrings[2]
    struc = time.strptime(dateString, '%Y %b %d')
    startDate = datetime.date(struc.tm_year, struc.tm_mon, struc.tm_mday)
    ''' Create CanAva object,and add it to DB'''
    ava_obj = CanAva(startDate)
    ''' Query Role Id firstly, the get the CanAva obj'''
    role_obj = db_session.query(Role).filter(Role.email == user_email,
                                             Role.role == 'canvasser').first()
    role_obj.roles_relation_2.append(ava_obj)
    db_session.commit()

    logging.info("updating availability for email " + user_email + " with " +
                 " the date on " + start)
    theLock.release()
    return 'update'
Beispiel #59
0
def post_user_post_comment(user_id, post_id):
    post = Post.query.filter(Post.post_id == post_id).first()
    if post is None:
        return Response('{"error":"post not found"}', status=404)

    user = User.query.filter(User.user_id == user_id).first()
    if user is None:
        return Response('{"error":"user not found"}', status=404)

    commentjson = request.get_json()
    commentjson["user_id"] = user_id
    commentjson["post_id"] = post_id

    newcomment = Comment.fromjson(commentjson)

    db_session.add(newcomment)
    db_session.commit()
    response = Response(status=201)
    response.headers["Location"] = "/users/" + str(
        newcomment.user_id) + "/posts/" + str(
            newcomment.post_id) + "/comments/" + str(newcomment.comment_id)
    return response
Beispiel #60
0
    def import_usage(self):
        with open('usage-hourly.json') as usage_file:
            usage_data = json.load(usage_file)

        for usage in usage_data['value']:
            instance_data = json.loads(usage['properties']['instanceData'])
            resourceUri = str(
                instance_data['Microsoft.Resources']['resourceUri']).split(
                    sep='/')
            record = AzureUsage(
                resourceUri[4], resourceUri[6], resourceUri[8],
                usage['properties']['subscriptionId'],
                datetime.strptime(usage['properties']['usageStartTime'],
                                  '%Y-%m-%dT%H:%M:%S+00:00'),
                datetime.strptime(usage['properties']['usageEndTime'],
                                  '%Y-%m-%dT%H:%M:%S+00:00'),
                usage['properties']['meterName'],
                usage['properties']['meterCategory'],
                usage['properties']['meterId'],
                usage['properties']['quantity'])
            db_session.add(record)
        db_session.commit()