Example #1
0
def register_post():
    form = RegistrationForm(request.form)
    if form.validate():
        user = session.query(User).filter_by(username=form.username.data).first()
        if user:
            flash('That username is already in use', 'danger')
            return redirect(url_for('register_get'))
        user = session.query(User).filter_by(email=form.email.data).first()
        if user:
            flash('That email is already in use', 'danger')
            return redirect(url_for('register_get'))
        
        newuser = User(username=form.username.data,
                email=form.email.data,
                password=generate_password_hash(form.password.data)
                )
        if form.fname.data and form.lname.data:
            newuser.realname = form.fname.data + form.lname.data
        elif form.fname.data:
            newuser.realname = form.fname.data
        elif form.lname.data:
            newuser.realname = form.lname.data
        session.add(newuser)
        session.commit()
        flash('Thanks for registering!', 'success')
        return redirect(url_for('login_get'))
    else:
        flash_errors(form)
        return render_template('register.html', form=form)
Example #2
0
def posts_put():
    """  Endpoint to post blog posts """

    # Construct the request data object
    data = request.json
    
    # First validate data object is valid JSON
    # If not valid return 422 error
    try:
        validate(data, post_schema)
    except ValidationError as error:
        data = {"message": error.message}
        return Response(json.dumps(data), 422, mimetype="application/json")        

    
    # Create data object from the request 
    data = request.json

    # Post data object to database
    post = models.Post(title=data["title"], body=data["body"])
    session.add(post)
    session.commit()

    # Response to client of successful post
    data = json.dumps(post.as_dictionary())
    headers = {"Location": url_for("post_get", id=post.id)}
    return Response(data, 201, headers=headers,
                    mimetype="application/json")
Example #3
0
def add_poi_post():
    form = POIForm(request.form)
    if form.validate():
        location = session.query(POI).filter_by(address=form.address.data).first()
        if location:
            flash('That location is already in the database!', 'warning')
            return redirect(url_for('add_poi_get'))
        lat, lng = geocode(form.address.data)
        if lat and lng:
            poi = POI(name=form.name.data,
                category=form.category.data,
                address=form.address.data,
                latitude=lat,
                longitude=lng,
                desc=form.desc.data)
            session.add(poi)
            session.commit()
            user = session.query(User).get(int(current_user.get_id()))
            user.poi_assocs.append(UserPOI(poi=poi, upvote=1))
            session.commit()
            flash('You added a new place!', 'success')
            return redirect(url_for('index'))
        else:
            flash('Google Maps could not find that address. Try again!',
                'warning')
            return render_template('add_poi.html', form=form)

    else:
        flash_errors(form)
        return render_template('add_poi.html', form=form)
Example #4
0
def authenticate_to_game(game_id):
    data = request.get_json(force=True)
    try:
        auth = authentication.Authentication()
        user_data = auth.user_from_identifier(data["authenticate"]["identifier"])
        users = models.User.query.filter_by(username=user_data["username"])

        if users.length > 0:
            # User is already registered
            user_id = users.first().id
        else:
            # User is not registered, register them
            register_user(user_data=user_data)
            user_id = models.User.query.filter_by(username=user_data["username"]).first().id

        game = models.Game.query.filter_by(id=game_id).first()
        score = models.Score(user_id=user_id, game_id=game.id)
        db.add(score)
        db.commit()

        response = return_success()
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
Example #5
0
def editShelter(key):
    editShelter = session.query(Shelter).filter_by(id = key).one()

    if request.method == 'POST':

        editShelter.name = request.form['name']
        editShelter.address = request.form['address']
        editShelter.city = request.form['city']
        editShelter.state = request.form['state']
        editShelter.zipCode = request.form['zipcode']
        editShelter.website = request.form['website']
        editShelter.current_occupancy = request.form['occupancy']
        editShelter.maximum_capacity = request.form['capacity']
        print editShelter.serialize
        session.add(editShelter)
        session.commit()

        flash("Shelter edited!")
        return redirect(url_for('viewShelter', key = key))

    else:
        return render_template(
            'edit.html',
            viewType = 'shelter',
            key = key,
            traits = editShelter.traits
        )
Example #6
0
def createUser(login_session):
    """Add a User to the database using the current information stored in the
    login session.

    Args:
        login_session (dict): Dictionary containing information about the current
        login session, including the user's profile information from Google+

    Returns:
        int: The user_id from the newly created record in the User table in
            the database.

    """
    print "Creating User"
    newUser = User(
        name=login_session['username'],
        email=login_session['email'],
        picture=login_session['picture']
    )

    session.add(newUser)
    session.flush()
    session.commit()

    return newUser.id
def file_post():
	#try to access uploaded file from Flask's request.files dictionary
	file = request.files.get("file")
	if not file:
		data = {"message": "Could not find file data"}
		return Response(json.dumps(data), 422, mimetype="application/json")

	#secure_filename() --> function(from Werkzeug) which creates a safe version of the filename supplied by client
	filename = secure_filename(file.filename)
	#use the secure filename to create a File object and add it to the database and commit
	db_file = models.File(filename=filename)
	session.add(db_file)
	session.commit()
	#save file to an upload folder using our upload_path() function
	file.save(upload_path(filename))

	#return file information
	data = db_file.as_dictionary()

	"""View how data above looks
	print ("file data from file_post() is {}".format(data))
	print ("")
	print("Response data is {}".format(json.dumps(data)))
	"""
	return Response(json.dumps(data), 201, mimetype="application/json")
Example #8
0
def newPuppy():

    if request.method == 'POST':
        newProfile = Profile(
            name = request.form['pupname'],
            weight = request.form['weight'],
            gender = request.form['gender'],
            picture = random.choice(puppy_images),
            dateOfBirth = datetime.strptime(request.form['birthday'], "%Y-%m-%d"),
            description = request.form['description'],
            specialNeeds = request.form['needs']
        )

        session.add(newProfile)

        new_puppy = Puppy(
            shelter_id = randint(1,5),
            profile = newProfile)

        session.add(new_puppy)
        session.commit()

        flash("New puppy created!")
        return redirect(url_for('viewPuppy', key = newPuppy.id))

    else:
        return render_template(
            'new.html',
            viewType = "puppy",
            traits = Puppy.defaultTraits()
        )
def songs_post():
    # Add a new song to the database 
    db_song = models.Song(file_id=file.id)
    session.add(db_song)
    session.commit()
    data = db_song.as_dictionary()
    return Response(json.dumps(data), 201, mimetype="application/json")
Example #10
0
def get_request_error_results(**kwargs):
    q_list = []
    if kwargs['product_category'] == 'HOTELS':
        q_list = queries.hotel_queries
    elif kwargs['product_category'] == 'FLIGHTS':
        q_list = queries.flight_queries
    else:
        q_list = queries.car_queries

    for q in q_list:
        try:
            q['query'] = q['query'].format(**kwargs)
            data = get_data(q['query'])
        except vp.errors.QueryError as e:
            data = [{'error': e.error_response.error_message()},{'error': e.sql}]
        for row in data:
            for key in row:
                row[key] = str(row[key])
        result = RequestErrorResult(result=json.dumps({'name': q['name'], 'description': q['description'], 'query': q['query'], 'data': data}), 
                                    request_id=kwargs['request_id'])
        session.add(result)
        session.commit()
    final = RequestErrorResult(result=json.dumps({'data':[{"end": "end"}]}), 
                               request_id=kwargs['request_id'])
    session.add(final)
    session.commit()
Example #11
0
def song_post():
  """ add a new song """
  data = request.json
  
  # Check that the JSON supplied is valid
  # If not you return a 422 Unprocessable Entity
  try:
    validate(data, song_schema)
  except ValidationError as error:
    data = {"message": error.message}
    return Response(json.dumps(data), 422, mimetype="application/json")
  
  # Get the file from the database
  file = session.query(models.File).get(data["file"]["id"])
  
  # If the file does not exist, respond with a 404
  if not file:
    message = "Could not find file with id {}".format(data["file"]["id"])
    data = json.dumps({"message": message})
    return Response(data, 404, mimetype="application/json")    
  
  # Add the new song to the database
  song = models.Song(file=file)
  session.add(song)
  session.commit()
  
  # Return a 201 Created, containing the song as json
  data = json.dumps(song.as_dictionary())
  headers = {"Location": url_for("song_get", id=song.id)}
  return Response(data, 201, headers=headers, mimetype="application/json")
Example #12
0
def add_flavor():
    """ Add a flavor to the DB """
    # Get creator user name passed with request as argument
    creator = request.args.get("creator")
    # Get flavor name passed as argument
    flavor_name = request.args.get("flavor")

    # Try to get the flavor being added from the DB
    data = session.query(Flavor).filter(Flavor.name == flavor_name).all()
    # If you got the item back from the DB, issue a warning
    if data:
        message = {"message": "Entry matching request already exists in database."}
        return Response(json.dumps(message), 422, mimetype="application/json")
    # Otherwise create the flavor
    flavor = Flavor()
    flavor.name = flavor_name
    flavor.creator = creator
    # Add it to the DB
    session.add(flavor)
    session.commit()
    # Obtain the dict info for the created object
    data = flavor.as_dictionary()
    # And create the header for the new ingredient
    headers = {"Location": "/api/flavor/id/{}".format(flavor.id)}
    # Return that with 201 created
    return Response(json.dumps(data), 201,
                    headers=headers,
                    mimetype="application/json")
def posts_put(id):

    data = request.json                                      
    # Check that the JSON supplied is valid
    # If not we return a 422 Unprocessable Entity
    try:
        validate(data, post_schema)
    except ValidationError as error:
        data = {"message": error.message}
        return Response(json.dumps(data), 422, mimetype="application/json")                               
          
    post = session.query(models.Post).get(id)
    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")
                                          
    post.title = data["title"]
    post.body = data["body"]
    session.add(post)
    session.commit()
                                          
    # Return a 201 Created, containing the post as JSON and with the
    # Location header set to the location of the post
    data = json.dumps(post.as_dictionary())
    headers = {"Location": url_for("post_get", id=post.id)}
    return Response(data, 201, headers=headers,
                    mimetype="application/json")
Example #14
0
def newCategory():
    """Allow an Authorized User to add a new Category or Process the form for
    adding a new Category.

    Returns:
        For a GET operation returns a Web View containing a form for entering
        data for the new user.

        A successful POST request directs presents a View of the new Category.

    """
    # Only an Authenticated User can add New Categories
    if isActiveSession() is False:
        return redirect(url_for("listCategory"))

    # Process the New Category Form and add it to the Database
    if request.method == "POST":
        newCategory = Category(user_id=getSessionUserInfo()["id"], name=request.form["name"])

        session.add(newCategory)
        session.commit()

        flash("New Category created!")
        # Display the Information for the new Category
        return redirect(url_for("viewCategory", key=newCategory.id))

    else:
        return render_template(
            "generic.html",
            modelType="category",
            viewType=os.path.join("partials", "new.html"),
            traits=Category.defaultTraits(),
        )
Example #15
0
def edit_post_post(id):
	post = session.query(Post).filter(Post.id == id).one()
	post.title = request.form["title"]
	post.content = mistune.markdown(request.form["content"])
	session.add(post)
	session.commit()
	return redirect(url_for('posts'))
Example #16
0
def newUser():
    """Present an Authorized Web User with a View for adding a new user.

    Returns:
        For a GET operation returns a Web View containing a form for entering
        data for the new user.

        A successful POST request directs presents a View of the new Record.

    """
    if isActiveSession() is False:
        return redirect(url_for("listUser"))

    # Process New User Form Submission
    if request.method == "POST":
        # Add the new user record to the database
        newUser = User(name=request.form["name"])

        session.add(newUser)
        session.commit()

        flash("New User created!")

        # Redirect to the User View
        return redirect(url_for("viewUser", key=newUser.id))

    # Present the New User Form
    else:
        return render_template(
            "generic.html", modelType="user", viewType=os.path.join("partials", "new.html"), traits=User.defaultTraits()
        )
Example #17
0
def editProfile(key):

    editProfile = session.query(Profile).filter_by(id = key).one()

    if request.method == 'POST':
        editProfile.name = request.form['name']
        editProfile.weight = request.form['weight']
        editProfile.gender = request.form['gender']
        editProfile.dateOfBirth = datetime.strptime(request.form['birthday'], "%Y-%m-%d")
        editProfile.description = request.form['description']
        editProfile.specialNeeds = request.form['needs']

        session.add(editProfile)
        session.commit()

        flash("Profile edited!")
        return redirect( url_for('viewProfile', key = key) )

    else:
        return render_template(
            'edit.html',
            viewType = 'profile',
            key = key,
            traits = editProfile.traits
        )
Example #18
0
def newShelter():
    if request.method == 'POST':
        newShelter = Shelter(
            name = request.form['name'],
            address = request.form['address'],
            city = request.form['city'],
            state = request.form['state'],
            zipCode = request.form['zipcode'],
            website = request.form['website'],
            current_occupancy = request.form['occupancy'],
            maximum_capacity = request.form['capacity']
        )

        session.add(newShelter)
        session.commit()

        flash("New Shelter created!")
        return redirect(url_for('viewShelter', key = newShelter.id))

    else:
        return render_template(
            'new.html',
            viewType = "shelter",
            traits = Shelter.defaultTraits()
        )
Example #19
0
def songs_post():
    """ Post a new song to database """

    data = request.json

    # Check for valid JSON. If not available, return 422, Unprocessable Entity
    try:
        validate(data, post_schema)
    except ValidationError as error:
        data = json.dumps({"message": error.message})
        return Response(data, 422, mimetype="application/json")

    file_id = data["file"]["id"]
    song_file = session.query(models.File).get(file_id)

    if not song_file: # File with id = file_id is not in database
        message = "Could not find song file with file id {}".format(file_id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")
        
    song = models.Song(file_id=file_id)
    session.add(song)
    session.commit()
    data = json.dumps(song.as_dictionary())
    return Response(data, 201, mimetype="application/json")
Example #20
0
def put_posts(id):
	""" Edit an existing post """

	data = request.json

	# Check JSON validity
	try:
		validate(data, post_schema)		
	except ValidationError as error:
		data = {"message": error.message}
		return Response(json.dumps(data), 422, mimetype="application/json")

	post = session.query(models.Post).filter_by(id=id).one()
	post.title = data["title"]
	post.body = data["body"]

	session.add(post)
	session.commit()

	#Return a 201 created, containing the post as JSON and with
	#the Location header set to the location of the post

	data = json.dumps(post.as_dictionary())
	headers = {"Location": url_for("post_get", id=post.id)}
	return Response(data, 201, headers=headers,
		mimetype="application/json")
Example #21
0
def songs_post():
    """ Add a new song - after file is uploaded """
    # Get JSON from the request
    data = request.json

    # Check that the JSON supplied is valid
    # If not you return a 422 Unprocessable Entity
    try:
        validate(data, file_schema)
    except ValidationError as error:
        data = {"message": error.message}
        return Response(json.dumps(data), 422, mimetype="application/json")

    # Extract the file data from the request
    file = data["file"]
    # Verify that this file exists in the database
    db_file = session.query(models.File).get(file["id"])

    # Create the song object, linking the file_id
    song = models.Song(file_id=file["id"])
    # Add the song to the session and commit it
    session.add(song)
    session.commit()

    # Return a 201 Created, containing the post as JSON and with the
    # Location header set to the location of the post
    data = json.dumps(song.as_dictionary())
    headers = {"Location": url_for("songs_get")}
    return Response(data, 201, headers=headers, mimetype="application/json")
Example #22
0
def post_put(id):
    """ Updating or editing a single post endpoint """
    # Get the post from the database
    post = session.query(models.Post).get(id)

    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    data = request.json

    # Check that the JSON supplied is valid
    # If not we return a 422 Unprocessable Entity
    try:
        validate(data, post_schema)
    except ValidationError as error:
        data = {"message": error.message}
        return Response(json.dumps(data), 422, mimetype="application/json")

    # Add the post to the database
    post = models.Post(title=data["title"], body=data["body"])
    session.add(post)
    session.commit()

    # Return the post as JSON
    data = json.dumps(post.as_dictionary())
    headers = {"Location": url_for("post_get", id=post.id)}
    return Response(data, 201, headers=headers,
                    mimetype="application/json")
Example #23
0
def add_post_post():
    post = Post(
        title=request.form["title"],
        content=mistune.markdown(request.form["content"])
    )
    session.add(post)
    session.commit()
    return redirect(url_for("posts"))
Example #24
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(email=form.email.data, password=form.password.data)
        session.add(user)
        session.commit()
        login_user(user, remember=True)
        return redirect("/")
    return render_template("register.html", form=form)
Example #25
0
def edit_post_post(blogid=1):
    post = session.query(Post).filter(Post.id==blogid).first()
    post.title = request.form["title"]
    post.content = mistune.markdown(request.form["content"])
    print 'post.title',post.title
    print 'post.content',post.content
    session.add(post)
    session.commit()
    return redirect(url_for("posts"))
Example #26
0
def add_post_post():
    post = Post(
        title=request.form["title"],
        content=request.form["content"],
        author=current_user,
        )
    session.add(post)
    session.commit()
    return redirect(url_for("posts"))
    def generatePreKeys(self):
        keyIdOffset = self.getNextPreKeyId()

        for i in range(0, self.BATCH_SIZE):
            keyId = (keyIdOffset + i) % self.MAX_PRE_KEY
            privkey, pubkey = genKey()
            session.add(PreKey(keyId=keyId, publicKey=pubkey, privateKey=privkey))

        self.setNextPreKeyId((keyIdOffset + self.BATCH_SIZE) % self.MAX_PRE_KEY)
Example #28
0
def edit_post_post(postId=None):
    post = session.query(Post).filter(Post.id==postId).all()[0]
    if (post.author.id != current_user.id):
        return redirect(url_for("posts"))    
    post.title = request.form["title"]
    post.content = mistune.markdown(request.form["content"])
    session.add(post)
    session.commit()
    return redirect(url_for("get_post", postId=post.id))
Example #29
0
def add_post_post():
	post = Post(
		title=request.form["title"],
		content=mistune.markdown(request.form["content"]),
		author=current_user
		)
	session.add(post)
	session.commit()
	return redirect(url_for('posts'))
def add_post_post():
    #create a new Post object
    post = Post(
        title=request.form["title"],
        content=mistune.markdown(request.form["content"]),
    )
    #add post to our session and commit to database
    session.add(post)
    session.commit()
    return redirect(url_for("posts"))
Example #31
0
def add_item():
    if request.method == 'POST':
        user = getUserInfo(login_session['user_id'])
        category_name = request.form['genre']
        category = session.query(Category).filter_by(
            name=str(category_name)).one()
        newItem = Item(title=request.form['title'],
                       description=request.form['description'],
                       category=category,
                       user_id=login_session['user_id'],
                       user=user)
        session.add(newItem)
        session.commit()
        flash("New item created!")
        return redirect(url_for('users.display_all'))
    else:
        return render_template('add_item.html')
Example #32
0
  def mutate(cls, instance, args, info):
    session.begin()

    new_comment = CommentModel(
      text = args.get('text'),
      user_id = args.get('user_id'),
      product_id = args.get('product_id'),
    )

    session.add(new_comment)

    session.commit()

    return CreateComment(
      comment=Comment(new_comment),
      ok=True,
    )
Example #33
0
def register_clock_in(user_id):
    """
    Register clock in for a teacher.
    :param user_id:
    :return: True or False
    """
    success = True
    try:
        spell = Spell(start=datetime.now())
        spell.user_id = user_id
        session.add(spell)
        session.commit()
    except Exception as exc:
        success = False
        logger.exception(exc)

    return success
Example #34
0
def signup():
    form = RegisterForm()

    if form.validate_on_submit():
        # check if user with same id exists
        hashed_password = generate_password_hash(form.password.data,
                                                 method='sha256')
        new_user = User(email=form.email.data,
                        username=form.username.data,
                        password=hashed_password)
        session.add(new_user)
        session.commit()

        return redirect(url_for('.login'))
        # return '<h1>' + form.username.data + ' ' + form.email.data + ' ' + form.password.data + '</h1>'

    return render_template('signup.html', form=form)
Example #35
0
def editAdopter(key):
    print "editAdopter: id = %s" % key
    edAdopter = session.query(Adopter).filter_by(id=key).one()

    if request.method == 'POST':
        edAdopter.name = request.form['name']

        session.add(edAdopter)
        session.commit()

        return redirect(url_for('viewAdopter', key=edAdopter.id))

    else:
        return render_template('edit.html',
                               viewType="adopter",
                               key=key,
                               traits=edAdopter.traits)
Example #36
0
def create_cluster(name_cluster, name_key, zone):
    """
    :name_cluster: Name new cluster
    :name_key: Name connection strint to aws in table connection
    :awsAccessKeyId: Access key id for access to aws
    :awsSecretKeyId: Secret key id for access to aws
    """
    logging.info("Creating cluster")
    try:
        session.add(ClusterTable(name_cluster, name_key, zone))
        session.commit()
    except:
        logging.error("Error add cluster to table")
        session.rollback()
        raise

    return Cluster(name_cluster)
Example #37
0
def deposit():

    animal_type = session.query(AnimalType).filter(AnimalType.name == request.form['type']).first()
    if not animal_type:
        flash('Sorry, we do not accept animals of this type', 'danger')
        return redirect(url_for('animals_list'))

    animal = Animal(animal_type_id=animal_type.id,
                    name=request.form['name'],
                    weight=request.form['weight'],
                    age=request.form['age'])
    try:
        session.add(animal)
        session.commit()
    except:
        flash('Error occured', 'danger')

    return redirect(url_for('animals_list'))
Example #38
0
 def post(self):
     """Create a new bucketlist."""
     parser.add_argument('list_name', help='List name cannot be blank')
     arg = parser.parse_args()
     if arg['list_name']:
         list_name = arg['list_name']
     else:
         return {'message': 'Invalid value passed.'}
     created_by = current_user.user_id
     bucketlistexist = session.query(BucketList).filter_by(
         list_name=list_name, creator=created_by).first()
     if bucketlistexist:
         return {'message': 'Bucketlist  already exists'}, 400
     else:
         bucketlist = BucketList(list_name=list_name, creator=created_by)
         session.add(bucketlist)
         session.commit()
         return marshal(bucketlist, bucketlists), 201
Example #39
0
    def on_message(self, room: Room, user: User, message: Message) -> None:
        """
        Triggers upon every chat message to parse commands, validate users, and save chat logs.

        :param Room room: Chatango room.
        :param User user: User responsible for triggering command.
        :param Message message: Raw chat message submitted by a user.

        :returns: None
        """
        chat_message = message.body.lower()
        user_name = user.name.title().lower()
        room_name = room.room_name.lower()
        self._check_blacklisted_users(room, user_name, message)
        self._get_user_data(room_name, user, message)
        self._process_command(chat_message, room, user_name, message)
        session.add(
            Chat(username=user_name, room=room_name, message=chat_message))
Example #40
0
def generate_token(bot, update, args):
    if len(args) == 1:
        token_value = str(uuid.uuid4().hex)
        valid_until = datetime.datetime.now() + datetime.timedelta(
            days=int(args[0]))
        valid_until_f = valid_until.strftime('%m.%d.%Y')

        token = Token(value=token_value, valid_until=valid_until.date())
        session.add(token)
        session.commit()

        update.message.reply_text("Here is the new token: \n\n"
                                  "```{}```\n\n"
                                  "Valid until: `{}`".format(
                                      token_value, valid_until_f),
                                  parse_mode=ParseMode.MARKDOWN)
    else:
        update.message.reply_text("Please, send me the number of days "
                                  "the token will be valid.")\
Example #41
0
 def put(self, list_id):
     """Modify existing bucketlist."""
     try:
         bucketlist = _get_bucketlist(list_id)
         parser.add_argument('list_name')
         arg = parser.parse_args()
         if arg['list_name']:
             bucketlist.list_name = arg['list_name']
         else:
             return {'message': 'Invalid value passed.'}
         session.add(bucketlist)
         session.commit()
         return {
             'message': 'Bucketlist {} has been modified'.format(list_id)
         }, 202
     except NoResultFound:
         return {
             'message': 'Bucketlist {} has not been found'.format(list_id)
         }, 404
Example #42
0
def submit_handler_3(user: User, update: Update, context: CallbackContext):
    todays_mwe = mwe_helper.get_todays_mwe(user.language)

    submit_category_1_submissions = [
        get_language_token(user.language, Tokens.FORM_SPECIAL_MEANING_TOGETHER)
        % get_mwe_words(todays_mwe),
        get_language_token(user.language,
                           Tokens.DOESNT_FORM_SPECIAL_MEANING_TOGETHER) %
        get_mwe_words(todays_mwe),
    ]

    if update.message.text in submit_category_1_submissions:
        if update.message.text == submit_category_1_submissions[0]:
            update.message.reply_text(
                get_language_token(user.language, Tokens.ARE_WORDS_SEPARATED) %
                get_mwe_words(todays_mwe),
                parse_mode=telegram.ParseMode.MARKDOWN,
                reply_markup=get_submit_category_2_keyboard_markup(
                    user.language, todays_mwe))
            context.user_data["state"] = "submit_example_type_2"
        else:
            submission = context.user_data["submission"]
            submission.category = "non-mwe"
            submission.users_who_reviewed = ''
            submission.user = user
            submission.language = user.language
            submission.mwe = todays_mwe
            session.add(submission)
            session.commit()
            del context.user_data["state"]
            del context.user_data["submission"]
            update.message.reply_text(
                get_language_token(user.language, Tokens.THANKS_FOR_SUBMISSION)
                % (get_random_congrats_message(user.language), 30),
                parse_mode=telegram.ParseMode.MARKDOWN,
                reply_markup=get_main_keyboard_markup(user.language))
    else:
        update.message.reply_text(
            get_language_token(user.language,
                               Tokens.ENTER_VALID_MWE_CATEGORY_1),
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=get_submit_category_1_keyboard_markup(
                user.language, todays_mwe))
def create_quiz(quiz: schemas.CreateQuizRequest):
    """Create a new quiz
    """
    new_quiz = models.Quiz(quiz.title, quiz.author)
    session.add(new_quiz)
    session.commit()

    for question in quiz.questions:
        new_question = models.Question(new_quiz.id, question.question_text,
                                       question.correct_answer,
                                       question.answer_one,
                                       question.answer_two,
                                       question.answer_three,
                                       question.answer_four)

        session.add(new_question)
    session.commit()
    session.refresh(new_quiz)

    return new_quiz
Example #44
0
def edit_item(item_name):
    item = session.query(Item).filter_by(title=item_name).one()
    if item.user_id == login_session['user_id']:
        if request.method == 'POST':
            if request.form['title']:
                item.title = request.form['title']
            if request.form['description']:
                item.description = request.form['description']
            category_name = request.form['genre']
            category = session.query(Category).filter_by(
                name=str(category_name)).one()
            item.category = category
            session.add(item)
            session.commit()
            flash("Item has been edited.")
            return redirect(url_for('users.display_all'))
        else:
            return render_template('edit_item.html', item_name=item.title)
    else:
        redirect(url_for('users.display_all'))
Example #45
0
def support_menu_state(message, user, is_entry=False):
    if is_entry:
        bot.send_message(
            message.chat.id,
            DICTIONARY[user.language]['support_menu_msg'],
            reply_markup=get_back_keyboard(language=user.language))
    else:
        if message.text == DICTIONARY[user.language]['back_btn']:
            return True, 'main_menu_state'
        else:
            support_request = SupportRequest(user_id=user.id,
                                             message=message.text[:300])
            session.add(support_request)
            session.commit()
            bot.send_message(
                message.chat.id,
                DICTIONARY[user.language]['sent_support_request_msg'])
            return True, 'main_menu_state'

    return False, ''
def add_best_bets():
    browser.get('https://sportsinsights.actionnetwork.com/best-bets/')
    time.sleep(7)
    a_s3 = browser.find_element_by_id('myTab1').find_elements_by_tag_name('a')[2]
    browser.execute_script('arguments[0].click()', a_s3)
    time.sleep(1)
    main_tab = browser.find_element_by_id('s3').find_elements_by_id('borderLayout_eRootPanel')[1]
    div_list = main_tab.find_element_by_class_name('ag-body-container').find_elements_by_css_selector(
        '.ag-row.ag-row-no-focus')
    for div in div_list:
        cell_list = div.find_elements_by_tag_name('div')
        new_best_bets = SportsInsightsBESTBETS(cell_list[0].get_attribute('innerHTML'),
                                               cell_list[1].get_attribute('innerHTML'),
                                               cell_list[2].get_attribute('innerHTML'),
                                               cell_list[3].get_attribute('innerHTML'),
                                               cell_list[4].get_attribute('innerHTML').replace(
                                                   '<b>', '').replace('</b>', ''),
                                               cell_list[5].get_attribute('innerHTML'))
        session.add(new_best_bets)
        print(new_best_bets)
Example #47
0
def newShelter():
    if request.method == 'POST':
        newShelter = Shelter(name=request.form['name'],
                             address=request.form['address'],
                             city=request.form['city'],
                             state=request.form['state'],
                             zipCode=request.form['zipcode'],
                             website=request.form['website'],
                             current_occupancy=request.form['occupancy'],
                             maximum_capacity=request.form['capacity'])

        session.add(newShelter)
        session.commit()

        flash("New Shelter created!")
        return redirect(url_for('viewShelter', key=newShelter.id))

    else:
        return render_template('new.html',
                               viewType="shelter",
                               traits=Shelter.defaultTraits())
Example #48
0
def create_user():
    form = NewUserForm(request.form)
    sys.stderr.write("FORM IS validated? %s \n" % form.validate())
    if form.validate() and request.method == 'POST':
        flash("Successfully created user {}".format(form.username.data))
        users = session.query(User).filter(
            User.username == form.username.data).all()
        if users:
            flash(
                "Username {} already exists; please choose a different username"
                .format(form.username.data))
        else:
            new_user = User(username=form.username.data,
                            password=form.password.data,
                            is_admin=form.is_admin.data)
            session.add(new_user)
            session.commit()
            return redirect('index')
    elif request.method == 'POST':
        flash("Limit entries to 3-8 characters")
    return render_template('create_user.html', form=form, is_admin=is_admin)
Example #49
0
 def solve_n_queens(self):
     q = session.query(Queen).filter_by(n=self.N)
     number_of_solutions = -1
     for x in q:
         number_of_solutions = x.number_of_solutions
     if number_of_solutions != -1:
         print("Number of solutions: ", number_of_solutions)
         return number_of_solutions
     else:
         k = 0
         board = [0] * self.N
         queen = Queen(n=self.N, number_of_solutions=0)
         session.add(queen)
         session.commit()
         if self.find_solution(board, k) == False:
             print("There is not solution for this N")
             return False
         print("Number of solutions: ", self.solutions)
         queen.number_of_solutions = self.solutions
         session.commit()
     return self.solutions
Example #50
0
def post():
    # user_id
    # promise_id -1ならNone
    # created_at 2012-12-29 13:49:37の形式

    user = session.query(User).filter(
        User.id == request.json['user_id']).one_or_none()
    promise = session.query(Promise).filter(
        Promise.id == request.json['promise_id']).one_or_none()

    motion = Motion()
    motion.user_id = user.id
    motion.promise_id = None if promise is None else promise.id
    motion.created_at = DT.strptime(request.json['created_at'],
                                    '%Y-%m-%d %H:%M:%S')

    session.add(motion)
    session.commit()
    session.close()

    return jsonify({'results': 'OK'}), 200
Example #51
0
    def post(self):
        data = Menu.parser.parse_args()
        #경로를 위한 변수 설정
        server_path = '' 

        data = request.form
        if 'category_pk' not in data.keys():
            return Response(status = 404)

        if 'image' in request.files:
            #local_path 저장할 경로, server_path 이미지 접근 가능 url 저장
            image = request.files['image']
            local_path = os.path.join(saveImgDir, 'main/', secure_filename(image.filename))
            image.save(local_path)
            server_path = os.path.join(serverImgDir, 'main/', secure_filename(image.filename))
        
        main_menu = models.Menu()
        
        #request에 이미지 파일이 존재하면 객체 menu_image필드에 server_path 저장 
        if server_path != '':
            main_menu.menu_image = server_path
        
        
        for i in data.keys():
            if i == 'category_pk':
                main_menu.category_pk = data['category_pk']
            elif i == 'menu_name':
                main_menu.menu_name = data['menu_name']
            elif i == 'menu_price':
                main_menu.menu_price = data['menu_price']
            elif i == 'menu_soldout':
                main_menu.menu_soldout = data['menu_soldout']
            elif i == 'menu_description':
                main_menu.menu_description = data['menu_description']
        
        session.add(main_menu)
        session.flush()
        session.commit()
        session.close()
        return Response(status = 201)
Example #52
0
def save_to_database(data):
    try:
        user = session.query(User).filter_by(id=str(data["user"]["id"])).one()
    except NoResultFound:
        user = create_user_helper(data["user"])
        session.add(user)

    hashtag_results = []
    hashtags = data["entities"]["hashtags"]
    for hashtag in hashtags:
        hashtag = hashtag["text"].lower()
        try:
            hashtag_obj = session.query(Hashtag).filer_by(text=hashtag).one()
        except NoResutlFound:
            user = create_
            hashtag_obj = Hashtag(text=hashtag)
            session.add(hashtag_obj)

        hashtag_results.append(hashtag_obj)

        tweet = create_tweet_helper(data, user)

        for hashtag in hashtag_results:
            tweet.hashtags.append(hashtag)

        session.add(tweet)
        session.commit()
Example #53
0
def save_to_database(data):
    try:
        user = session.query(User).filter_by(id=str(data['user']['id'])).one()
    except NoResultFound:
        user = create_user_helper(data['user'])
        session.add(user)

    hashtag_results = []
    hashtags = data['entities']['hashtags']
    for hashtag in hashtags:
        hashtag = hashtag['text'].lower()
        try:
            hashtag_obj = session.query(Hashtag).filter_by(text=hashtag).one()
        except NoResultFound:
            hashtag_obj = Hashtag(text=hashtag)
            session.add(hashtag_obj)

        hashtag_results.append(hashtag_obj)

    tweet = create_tweet_helper(data, user)

    for hashtag in hashtag_results:
        tweet.hashtags.append(hashtag)

    session.add(tweet)
    session.commit()
Example #54
0
def test_get_all():
    item1 = TodoItem(completed=False, text="Test item text")
    session.add(item1)
    item2 = TodoItem(completed=False, text="Test item two text")
    session.add(item2)
    item3 = TodoItem(completed=True, text="Test item three text")
    session.add(item3)
    session.flush()
    response = client.get("/todo/")
    actual = response.json()
    expected = {
        "status":
        "success",
        "data": [
            {
                "id": item1.id,
                "completed": False,
                "text": "Test item text"
            },
            {
                "id": item2.id,
                "completed": False,
                "text": "Test item two text"
            },
            {
                "id": item3.id,
                "completed": True,
                "text": "Test item three text"
            },
        ],
    }
    assert actual == expected
Example #55
0
def file_post():
    # Attempt to obtain the file uploaded file from Flask's request.files dict
    file = request.files.get("file")
    # If the file is not found, return an error
    if not file:
        data = {"message": "Could not find file data"}
        return Response(json.dumps(data), 422, mimetype="application/json")
    # Werkzeug secure_filename function provides safe version of file name
    # For instance ../../../etc/passwd is replaced by etc_passwd
    filename = secure_filename(file.filename)
    # Create file object with safe filename
    db_file = models.File(name=filename)
    # Add the file object to the session and commit
    session.add(db_file)
    session.commit()
    # Save the file to the upload path using the safe file name
    file.save(upload_path(filename))

    # Create a dict object of file
    data = db_file.as_dictionary()
    # Return a response with 201 CREATED
    return Response(json.dumps(data), 201, mimetype="application/json")
Example #56
0
    def post(self):
        data = request.form
        server_path = ''
        print(3)

        if 'category_pk' not in data.keys():
            return Response(status=404)

        if 'image' in request.files:
            image = request.files['image']
            print(image.filename)
            local_path = os.path.join(saveImgDir, 'main/',
                                      secure_filename(image.filename))
            image.save(local_path)
            print(local_path)
            server_path = os.path.join(serverImgDir, 'main/',
                                       secure_filename(image.filename))

        main_menu = models.Menu()

        if server_path != '':
            main_menu.menu_image = server_path

        for i in data.keys():
            if i == 'category_pk':
                main_menu.category_pk = data['category_pk']
            elif i == 'menu_name':
                main_menu.menu_name = data['menu_name']
            elif i == 'menu_price':
                main_menu.menu_price = data['menu_price']
            elif i == 'menu_soldout':
                main_menu.menu_soldout = data['menu_soldout']
            elif i == 'menu_description':
                main_menu.menu_description = data['menu_description']

        session.add(main_menu)
        session.flush()
        session.commit()
        return Response(status=201)
def send_welcome(message):
    try:
        logger.debug(f"/start | user_id: {message.from_user.id}")
        user = session.query(User).filter_by(user_id=message.from_user.id).first()

        if user is None:
            user = User(
                user_id=message.from_user.id,
                username=message.from_user.username,
                first_name=message.from_user.first_name,
                last_name=message.from_user.last_name,
                state='login_state'
            )
            session.add(user)
            session.commit()
        else:
            user.state = 'main_menu_state'
            session.commit()

        get_state_and_process(message, user, True)
    except Exception as e:
        logger.error(e, exc_info=True)
Example #58
0
def cli(n, l):
    """
    backup with 7zip and python
    Frederico Sales <*****@*****.**>.
    Use:
    bck -n backupname -l path/folder/.../folder
    """
    _date = datetime.now
    _now = _date().strftime("_%d-%m-%Y_%H:%m.7z")
    config = ConfigParser()
    config.read(_Loc() + '/bck.cfg')

    if n != None and l != None:
        _bck = n + _now
        cmd = "7z a " + _bck + " " + l
        os.system(cmd)

        # md5sum
        md5sum = "md5sum " + _bck
        os.system(md5sum)

        # move backup to url
        _bck_path = config.get("BACKUP", "BACKUP_PATH")
        _mv = "mv " + os.getcwd() + "/" + _bck + " " + _bck_path
        os.system(_mv)

        # md5sum to db
        _file = _bck_path + "/" + _bck
        md = open(_file, 'rb').read()
        check = hashlib.md5(md).hexdigest()

        _bck_ = Backup(name=_bck, path=l, md5=check)
        session.add(_bck_)
        session.commit()
        session.close()

        click.echo('backup ends successfully.')
    else:
        click.echo('catastrophic failure.')
Example #59
0
 def post(self, list_id):
     """Add a new item to a bucketlist."""
     try:
         bucketlist = _get_bucketlist(list_id)
         parser.add_argument('item_name')
         arg = parser.parse_args()
         if arg['item_name']:
             item = arg['item_name']
         else:
             return {'message': 'Invalid value passed.'}
         bucketlistitem = BucketListItems(item_name=item,
                                          bucket_id=bucketlist.list_id)
         session.add(bucketlistitem)
         session.commit()
         return {
             'message':
             '{0} has been added to Bucketlist {1}'.format(item, list_id)
         }, 201
     except NoResultFound:
         return {
             'message': 'Bucketlist does not exist'.format(list_id)
         }, 404
Example #60
0
def posts_post():
    """ Add a new post """
    data = request.json

    # check that the JSON supplied is valid
    # if not you return a 422 Unprocessable Entity
    try:
        validate(data, post_schema)
    except ValidationError as error:
        data = {"message": error.message}
        return Response(json.dumps(data), 422, mimetype="application/json")

    # add the post to the database
    post = models.Post(title=data["title"], body=data["body"])
    session.add(post)
    session.commit()

    # return a 201 Created, containing the post as JSON and with the
    # location header set to the location of the post
    data = json.dumps(post.as_dictionary())
    headers = {"Location": url_for("post_get", id=post.id)}
    return Response(data, 201, headers=headers, mimetype="application/json")