def song_edit(id): song = session.query(models.Song).get(id) if not song: message = "Could not find song with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") song_file = session.query(models.File).filter_by(id=song.file_id).first() data = request.json song_file.filename = data["filename"] session.commit() """Print outs to veiw how data looks during execution above print("print outs from song_edit()") print("Orig son file data is {}".format(song.as_dictionary())) print("Orig file data is {}".format(song_file.as_dictionary())) print("data from test is showing as {}".format(data)) """ data = json.dumps(song.as_dictionary()) """Print out to see how data above looks print("song_edit() final response data") """ headers = {"Location": url_for("song_get", id=id)} return Response(data, 201, headers=headers, mimetype="application/json")
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")
def post(): # schema = {'type': 'object', # 'properties': # {'id': {'type': 'integer', 'minimum': 0}}, # 'required': ['id'] # } # try: # validate(request.json, schema) # except ValidationError as e: # return jsonify({'msg': e.message}), 400 # return str(type(request.json['id'])) user = session.query(User).filter( User.id == request.json['id']).one_or_none() if user is None: return jsonify({'msg': 'User Not Found'}), 404 pull = Pull(user_id=user.id) session.add(pull) session.commit() session.close() return jsonify({'id': request.json['id']}), 200
def delete_movie(movie_id): movie = session.query(Movie).filter(Movie.id == movie_id).first() if not movie: return make_response( jsonify({ 'response': 'Movie not found', 'status': 404 })) session.delete(movie) try: session.commit() except Exception as e: return make_response( jsonify({ 'Error': 'Movie was not deleted', 'status': 500 }), 500) return make_response( jsonify({ 'response': 'Movie has been deleted', 'status': 200 }), 200)
def insertdd(): # walkをinsert # for i in range(1, 13): # hour = random.randint(8, 17) # miniute = random.randint(0, 59) # start_walk_datetime = datetime(2018, 5, i, hour, miniute, 0) # end_walk_datetime = start_walk_datetime + timedelta(minutes=40) # print(start_walk_datetime, end_walk_datetime) # # walk = Walk(user_id=1, started_at=start_walk_datetime, ended_at=end_walk_datetime) # session.add(walk) # session.commit() # session.close() for day in range(1, 13): for hour in range(8, 18): for miniute in range(0, 59): if random.randint(1, 3) % 2 == 0: pull_datetime = datetime(2018, 5, day, hour, miniute, 0) print(pull_datetime) # if random.randint(1, 11) % 2: # break # pull_datetime = datetime(2018, 4, day, hour, miniute, 0) # # print(pull_datetime) # pull = Pull(user_id=1, created_at=pull_datetime) session.add(pull) session.commit() session.close()
def editItem(item_id): """Render a page that displays an HTML form to edit an item Renders a page with an HTML form that allows the owner of the item to edit and update the item details. """ formList = session.query(Medium).all() editedItem = session.query(ArtItem).filter_by(id=item_id).one() if request.method == 'POST': if request.form['name']: editedItem.name = request.form['name'] if request.form['description']: editedItem.description = request.form['description'] if request.form['material']: editedItem.material = request.form['material'] if request.form['image_url']: editItem.image_url = request.form['image_url'] if request.form['video_url']: editItem.video_url = request.form['video_url'] if request.form['year']: editedItem.year = request.form['year'] session.add(editedItem) session.commit() return redirect(url_for('showForms')) else: return render_template( 'edit-item.html', item=editedItem, media=formList, userinfo=login_session )
def edit_post_post(id=1): post = session.query(Post) post = post.filter(Post.id == id).first() post.title=request.form["title"] post.content=mistune.markdown(request.form["content"]) session.commit() return redirect(url_for("posts"))
def delete_document(url): try: Document.query.filter(Document.url == url).delete() session.commit() return 'true' except: return 'Delete Failed'
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 )
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 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 )
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() )
def song_delete(): """ delete a song """ headers = {"Location": url_for("song_delete")} # get the data from the form data = request.json post_song = models.Song(song_name=data["song_name"],id=data["song_id"]) ## ask sam if we really need to post seperately. post_file = models.File(song_id=data["song_id"],file_name=data["file_name"],id=data["file_id"]) if session.query(models.Song).get(post_song.id): #consider adding a check here for duplicate fileID too del_song=session.query(models.Song).get(post_song.id) session.delete(del_song) del_file = session.query(models.File).get(post_file.id) session.delete(del_file) session.commit() else: print "************* ELSE ***************" session.rollback() session.flush() return Response(json.dumps({"status":"failed - that song doesnt exists"}),500,mimetype="application/json") return Response(json.dumps({"status":"deleted"}), 200, headers=headers, mimetype="application/json")
def delete(self, id): note = session.query(Note).filter(Note.id == id).first() if not note: abort(404, message="Note %s doesn't exist" % id) session.delete(note) session.commit() return note, 202
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 post_edit(id): """ Edit an existing post """ data = request.json # Get the post from the database post = session.query(models.Post).get(id) # 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") # Update the post post.title = data["title"] post.body = data["body"] session.commit() # Return a 200 Success, containing the edited post as a 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, 200, headers=headers, mimetype="application/json")
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() )
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")
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(), )
def edit_activity(activity_id=None): activity = session.query(Activity).get(activity_id) form = NewActivity(obj=activity) if request.method == 'POST': try: #start_time = datetime.strptime(str(form.start_time.data), '%b %d %Y %I:%M%p') #end_time = datetime.strptime(str(form.end_time.data), '%b %d %Y %I:%M%p') #duration = str(activity.end_time - activity.start_time) activity.title = form.title.data activity.activity = form.activity.data activity.start_time = form.start_time.data activity.end_time = form.end_time.data activity.duration = timedelta() activity.start_location = form.start_location.data activity.end_location = form.end_location.data activity.notes = form.notes.data activity.calories = form.calories.data if form.waypoints.data: activity.waypoints = form.waypoints.data session.commit() except ValueError as e: print e flash('Please enter date in correct format') return render_template('edit_activity.html', form=form) flash('Acvitity Edited!') return redirect(url_for('entries')) return render_template('edit_activity.html', form=form)
def update_post(id): """ Update a single post """ # check if the post exists, if not return a 404 with a helpful message post = session.query(models.Post).get(id) 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 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") post.title = data["title"] post.body = data["body"] session.commit() # return an OK 200, 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, 200, headers=headers, mimetype="application/json")
def admin_edit_cities_state(message, user, is_entry=False): current_cities = session.query(City.name).all() current_cities = [i for obj in current_cities for i in obj] if is_entry: bot.send_message( message.chat.id, 'Щоб змінити список міст, скопіюйте наступне повідомлення, та відредагуйте його.\nПоточний список міст:', reply_markup=get_back_keyboard(language=user.language)) bot.send_message(message.chat.id, '\n'.join(current_cities)) else: if message.text == DICTIONARY[user.language]['back_btn']: return True, 'admin_settings_state' else: new_cities = [] for city in message.text.split('\n'): if city not in current_cities: new_cities.append({ 'name': city, 'is_regional_center': False }) session.execute( insert(City).values(new_cities).on_conflict_do_nothing()) session.commit() bot.send_message(message.chat.id, 'Список міст оновлено') return True, 'admin_settings_state' return False, ''
def create_movie(): data = request.get_json() if data is None: return make_response( jsonify({ 'message': 'error creating movie, body is required', 'status': 500 }), 500) movie = Movie(title=data['title'], description=data['description'], genre_id=data['genre_id']) session.add(movie) try: session.commit() except Exception as e: return make_response( jsonify({ 'message': 'error creating movie, {}'.format(str(e)), 'status': 500 }), 500) return make_response(jsonify({ 'message': 'movie created', 'status': 201 }), 201)
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")
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 put(): # 受け取る値 # user_id userID -1ならNoneにして、達成を解除する。それ以外(正しいユーザID)なら普通にupdate # promise_id promiseID promise = session.query(Promise).filter(Promise.id == request.json['promise_id']).one_or_none() if request.json['user_id'] == -1: promise.one_side_done_user_id = None session.commit() session.close() return jsonify({'results': '約束の承認を解除'}), 200 if not (promise.master_user_id == request.json['user_id'] or promise.slave_user_id == request.json['user_id']): session.close() return jsonify({'results': '権限なし'}), 403 if promise.one_side_done_user_id is None: promise.one_side_done_user_id = request.json['user_id'] msg = '片方が承認しました' elif promise.one_side_done_user_id == request.json['user_id']: msg = '何もしないよ' else: promise.one_side_done_user_id = None promise.is_done = True msg = '約束の承認をお互いにしました' session.commit() session.close() return jsonify({'results': msg}), 200
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 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")
def post(): schema = { 'type': 'object', 'properties': { 'user_id': { 'type': 'integer', 'minimum': 0 } }, 'required': ['user_id'] } try: validate(request.json, schema) except ValidationError as e: return jsonify({'msg': e.message}), 400 user = session.query(User).filter( User.id == request.json['user_id']).one_or_none() if user is None: return jsonify({'msg': 'User Not Found'}), 404 walk = Walk(user_id=user.id) session.add(walk) session.commit() session.close() return jsonify({'walk_id': walk.id}), 200
async def main(): file_list = cj.ADD_FEE_LIST.keys() futures = [ asyncio.ensure_future( parse_zipcode( '{path}/{f_name}.txt'.format(path=path.DATA_PATH, f_name=f_name), cj.ADD_FEE_LIST[f_name])) for f_name in file_list ] futures.extend([ asyncio.ensure_future( parse_jeonnam_zipcode( '{path}/전라남도.txt'.format(path=path.DATA_PATH), cj.ADD_FEE_JEONAM)), asyncio.ensure_future( parse_incheon_zipcode( '{path}/인천광역시.txt'.format(path=path.DATA_PATH), cj.ADD_FEE_INCHEON)), asyncio.ensure_future( parse_jeju_zipcode( '{path}/제주특별자치도.txt'.format(path=path.DATA_PATH))) ]) results = await asyncio.gather(*futures) for result in results: session.bulk_save_objects([Address(**item) for item in result]) session.commit()
def insert_data(request): """Parse request json data and insert into db""" raw_data = request.get_data(as_text=True, cache=False) raw_data = json.loads(raw_data) # remove any whitespace and parse to dictionary sensor_data = raw_data['data'].replace(" ", "") sensor_data = (dict(x.split(':') for x in sensor_data.split(','))) # convert to floats and remove chars after '_' sensor_data = { k: float(v[:v.index('_')]) for k, v in sensor_data.items() if k != "minSinceStart" } print(sensor_data) # this timestamp is the time at which the sensor # pushed the data timestamp = raw_data['published_at'] particle_id = raw_data['coreid'] # get the sensor id from the users table if it exists sensor_owner = session.query(Users).filter_by( particle_str=particle_id).first() data_insert = Airdata(device_time=timestamp, temperature_C=sensor_data["Temp"], pressure_hPa=sensor_data["Press"], humidity_perc=sensor_data["Hum"], user=sensor_owner) session.add(data_insert) session.commit()
def posts_edit_post(id): """ 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") # Call up and edit the post post = session.query(models.Post).get(id) if data["title"]: post.title=data["title"] else: post.title=post.title if data["body"]: post.body=data["body"] else session.commit() # Return a 200 Created, containing the post as JSON and with the # Location header set to the location of the post data = json.dumps(post.as_dictionary()) return Response(data, 200, 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")
def song_post(): """ post a song """ headers = { "Location": url_for("song_post"), "Content-Type": "application/json" } ######### get the data from the form data = request.json post_song = models.Song( song_name=data["song_name"], id=data["song_id"]) ## ask sam if we really need to post seperately. post_file = models.File(song_id=data["song_id"], file_name=data["file_name"], id=data["file_id"]) if not session.query(models.Song).get( post_song.id ): #consider adding a check here for duplicate fileID too session.add_all([post_song, post_file]) session.commit() else: print "************* ELSE ***************" session.rollback() session.flush() return Response(json.dumps( {"status": "failed - that song already exists"}), 500, mimetype="application/json") return Response(stripUnicode(data), 200, headers=headers, mimetype="application/json")
def edit_post_post(post_id): post = session.query(Post).filter(Post.id == post_id).first() post.title = request.form["title"] post.content = mistune.markdown(request.form["content"]) #session.add(post) session.commit() return redirect(url_for("posts"))
def update_token(): schema = { 'type': 'object', 'properties': { 'token': { 'type': 'string', 'pattern': '^[0-9a-f]{64}$' } }, 'required': ['token'] } try: validate(request.json, schema) except ValidationError as e: session.close() frame = inspect.currentframe() abort(400, {'code': frame.f_lineno, 'msg': e.message, 'param': None}) user = session.query(User).filter( User.code == api_basic_auth.username()).one() user.token = request.json['token'] session.commit() session.close() return jsonify({'msg': 'OK'}), 200
def delete_post_post(post): posts= session.query(Post) posts= posts[post] session.delete(posts) session.commit() return redirect(url_for("posts"))
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()
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")
def add_account(bot, update, args, user_data): if len(args) == 1: phone_number = args[0] user = session.query(User).filter( User.tg_id == update.message.chat_id).first() tg_sessions = session.query(TelegramSession).filter( TelegramSession.user == user).all() phone_numbers = [s.phone_number for s in tg_sessions] if phone_number in phone_numbers: update.message.reply_text( "Sorry, this phone number already exists.") return ConversationHandler.END client = TelegramClient( os.path.join(config.TELETHON_SESSIONS_DIR, phone_number), user.api_id if user.api_id else config.TELEGRAM_API_ID, user.api_hash if user.api_hash else config.TELEGRAM_API_HASH) client.connect() result = client.send_code_request(phone_number, force_sms=True) client.disconnect() tg_session = TelegramSession(phone_number=phone_number, phone_code_hash=result.phone_code_hash, user=user) session.add(tg_session) session.commit() user_data['session_id'] = tg_session.id update.message.reply_text("Please, send the login code to continue") return LOGIN_CODE else: update.message.reply_text("Please, include the phone number to this " "command.") return ConversationHandler.END
def newItem(): """Render a page that displays an HTML form to create a new item Renders a page with an HTML form. When the form is submitted a new item is created in the database with the form values submitted. """ formList = session.query(Medium).all() if request.method == 'POST': newItem = ArtItem( name=request.form['name'], description=request.form['description'], material=request.form['material'], image_url=request.form['image_url'], video_url=request.form['video_url'], year=request.form['year'], medium_id=request.form['medium'], user_id=login_session['user_id'] ) session.add(newItem) session.commit() return redirect(url_for('showForms')) else: return render_template( 'new-item.html', media=formList, userinfo=login_session )
def confirm_tg_account(bot, update, user_data): code = update.message.text tg_session = session.query(TelegramSession).filter( TelegramSession.id == int(user_data['session_id'])).first() user = session.query(User).filter( User.tg_id == update.message.chat_id).first() client = TelegramClient( os.path.join(config.TELETHON_SESSIONS_DIR, tg_session.phone_number), user.api_id if user.api_id else config.TELEGRAM_API_ID, user.api_hash if user.api_hash else config.TELEGRAM_API_HASH) client.connect() try: client.sign_in(tg_session.phone_number, code, phone_code_hash=tg_session.phone_code_hash) tg_session.active = True update.message.reply_text('Account added successfully.') except Exception as e: update.message.reply_text('Error: {}.'.format(e)) path = os.path.join(config.TELETHON_SESSIONS_DIR, '{}.session'.format(tg_session.phone_number)) if os.path.exists(path): os.remove(path) session.delete(tg_session) session.commit() client.disconnect() return ConversationHandler.END
def update_song(id): """ Updating a single song """ # check if the song exists, if not return a 404 with a helpful message song = session.query(models.Song).get(id) if not song: message = "Could not find song 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, 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") song.song_file = data["song_file"] session.commit() # return an OK 200, containing the song as JSON with the # location header set to the location of the post data = json.dumps(song.as_dictionary()) headers = {"Location": url_for("post_get", id=song.id)} return Response( data, 200, headers=headers, mimetype="application/json" )
def send_email(**kwargs): from_address = FROM_ADDR to_address = kwargs.get('email') user_id = session.query(User.id).filter(User.email == to_address).first() if not user_id: raise ValueError("Enter Valid Email") msg = MIMEMultipart('alternative') msg['Subject'] = SUBJECT msg['From'] = from_address msg['To'] = to_address text = "Your Account for "+ to_address + " is successfully created \n \n Thanks \n Flask Blog" p1 = MIMEText(text, 'plain') msg.attach(p1) s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login("*****@*****.**", "Pankaj154!") s.sendmail(from_address, to_address, msg.as_string()) s.quit() email_obj = SystemEmailLog( user_id=user_id, from_address=from_address, to_address=to_address, cc=CC, subject=SUBJECT, message_body=kwargs, status=1 ) session.add(email_obj) session.commit()
def set_city_state(message, user, is_entry=False): if is_entry: bot.send_message( message.chat.id, DICTIONARY[user.language]['set_city_msg'], reply_markup=get_skip_keyboard(language=user.language)) else: if message.text == DICTIONARY[user.language]['skip_btn']: bot.send_message(message.chat.id, DICTIONARY[user.language]['signed_up_msg']) return True, 'main_menu_state' else: # check if given city exists in database current_cities = session.query(City.name).all() current_cities = [i for obj in current_cities for i in obj] if message.text in current_cities: user.city = message.text session.commit() bot.send_message(message.chat.id, DICTIONARY[user.language]['signed_up_msg']) return True, 'main_menu_state' else: bot.send_message(message.chat.id, DICTIONARY[user.language]['no_city_msg']) return True, 'main_menu_state' return False, ''
def session_clear(exception): if exception and session.is_active: session.rollback() else: session.commit() session.close()
def language_update_handler(user: User, update: Update, context: CallbackContext): if update.message.text == get_language_token(user.language, Tokens.LANGUAGE_ENGLISH): user.language = "en" session.commit() del context.user_data["state"] update.message.reply_text( get_language_token(user.language, Tokens.LANGUAGE_CHANGE_SUCCESSFUL), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=get_main_keyboard_markup(user.language)) elif update.message.text == get_language_token(user.language, Tokens.LANGUAGE_TURKISH): user.language = "tr" session.commit() del context.user_data["state"] update.message.reply_text( get_language_token(user.language, Tokens.LANGUAGE_CHANGE_SUCCESSFUL), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=get_main_keyboard_markup(user.language)) else: update.message.reply_text( get_language_token(user.language, Tokens.PLEASE_SELECT_VALID_LANGUAGE), parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=get_language_selection_keyboard_markup(user.language))
def _update_sets(api, session, tweet_set, start_num): """ Broke out a helper method so we didn't have to repeat the code for our last set. This helper method does the heavy lifting for us """ # Grab out just the tweet ids using a list comprehension tweet_ids = [tweet.tid for tweet in tweet_set] # Using the tweepy api, grab the updated tweets # `trim_user` drops user data updated_set = api.statuses_lookup(tweet_ids, trim_user=True) # iterate through update set for updated_tweet in updated_set: # the values we want to update fav_count = updated_tweet.favorite_count retweet_count = updated_tweet.retweet_count # Get the old tweet using it's twitter id (tid for short) tid = updated_tweet.id database_tweet = session.query(Tweet).filter_by(tid=tid).one() # update the tweet information in our database database_tweet.favorite_count = fav_count database_tweet.retweet_count = retweet_count # User feedback print('index: {}'.format(database_tweet.id)) print('favs: {} \t retweets: {}'.format(fav_count, retweet_count)) # save our changes to the database session.commit()
def populate_movies(): movies = request.json if movies is None: return make_response( jsonify({ 'message': 'error populating movies, body is required', 'status': 500 }), 500) for movie in movies: new_movie = Movie(title=movie['title'], description=movie['description'], genre_id=movie['genre_id']) session.add(new_movie) try: session.commit() except Exception as e: return make_response( jsonify({ 'message': 'error populating movies, {}'.format(str(e)), 'status': 500 }), 500) return make_response( jsonify({ 'message': 'movies populated', 'status': 201 }), 201)
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")
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()
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")
def update_song(id): """ Single song update endpoint """ # get the song from the database song = session.query(models.Song).get(id) # cehck if the song exisits # if not return a 404 with a helpful message if not song: message = "Could not find the song 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 return a 422 Unprocessable Entry try: validate(data, song_schema) except ValidationError as error: data = {"message": error.message} return Response(json.dumps(data), 422, mimetype="application/json") song.song_file_id = data["file"]["id"] session.commit() # return an OK 200 # containing the song as JSON and with the # location header set to the location of the song data = json.dumps(song.as_dictionary()) headers = {"Location": url_for("song_get", id=song.id)} return Response(data, 200, headers=headers, mimetype="application/json")
def update_post(id): """ Single post update endpoint """ # Get the post from the database post = session.query(models.Post).get(id) # Check if the post exists # If not return a 404 with a helpful message if not post: message = "Could not find the 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 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") post.title = data["title"] post.body = data["body"] session.commit() # return an OK 200, 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, 200, headers=headers, mimetype="application/json")
async def update_tasks(tasks: List[Task]): for new_task in tasks: task = session.query(TaskTable).filter( TaskTable.id == new_task.id).first() task.title = new_task.title session.commit() session.close()
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")
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)