def buyout_booking(bookingId): """buyout_booking # noqa: E501 :param bookingId: :type bookingId: int :rtype: bool """ sql_select_booking = 'select * from "Booking_Info" where "Id" = %s and "Status" = 0' sql_update_booking_status = 'update "Booking_Info" ' \ 'set "Status" = 1 where "Id" = %s ' # sql_insert_booking = 'insert into "Booking_Info"("Person_Id", "Transport_Id", "Count_Of_Persons", "Price") ' \ # 'values (%s, %s, %s, %s) try: with get_db_connection() as connection: with connection.cursor() as cursor: cursor.execute(sql_select_booking, (bookingId, )) booking = cursor.fetchone() if not booking: LOGGER.error('Booking not found') return False cursor.execute(sql_update_booking_status, (bookingId, )) except: LOGGER.info(traceback.format_exc()) print(traceback.format_exc()) return False return True
def music_library(): conn = utils.get_db_connection() cursor = conn.cursor() cursor.execute("SELECT name FROM songs") result = cursor.fetchall() conn.close() return flask.jsonify(result)
def post(self): if "logout" in flask.request.form: flask.session.pop("username", None) return flask.redirect(flask.url_for("login")) required = ["username", "passwd"] for r in required: if r not in flask.request.form: flask.flash("Error: {0} is required!".format(r)) return flask.redirect(flask.url_for("login")) username = flask.request.form["username"] passwd = flask.request.form["passwd"] conn = utils.get_db_connection() cursor = conn.cursor() cursor.execute( "SELECT username, password FROM users WHERE uploader = 1 AND username = %s", (username, )) result = cursor.fetchone() if result and result[1] == passwd: flask.session["username"] = username else: flask.flash("Username doesn't exist or incorrect password!") conn.close() return flask.redirect(flask.url_for("login")) conn.close() return flask.redirect(flask.url_for("uploader"))
def __init__(self): self.db_connection = get_db_connection() self.header = { 'Authorization': 'cdn.sspai.com', 'Host': 'cdn.sspai.com' } self.sspai_banner_url = 'https://cdn.sspai.com/' self.sspai_article_url = 'https://sspai.com/post/'
def register(): username = flask.request.json["username"] password = flask.request.json["password"] conn = utils.get_db_connection() cursor = conn.cursor() cursor.execute( "INSERT INTO users (username, password, uploader) VALUES (%s, %s, 0)", (username, password)) conn.commit() conn.close() return {}, 200
def validate_login(): username = flask.request.json["username"] password = flask.request.json["password"] conn = utils.get_db_connection() cursor = conn.cursor() cursor.execute( "SELECT username, password FROM users WHERE uploader = 0 AND username = %s", (username, )) result = cursor.fetchone() conn.close() if result and result[1] == password: return {}, 200 else: return {}, 401
def post(self): f = flask.request.files["file"] if is_mp3_file(f.filename): path = os.path.join(flask.current_app.instance_path, flask.current_app.config["UPLOAD_FOLDER"]) if not os.path.isdir(path): os.makedirs(path) f.save(os.path.join(path, secure_filename(f.filename))) conn = utils.get_db_connection() cursor = conn.cursor() cursor.execute("INSERT INTO songs (name) VALUES (%s)", (secure_filename(f.filename), )) conn.commit() conn.close() file = os.path.join(path, secure_filename(f.filename)) files = {"file": open(file, 'rb')} response = requests.post( "http://frontend_server:5000/upload_song/", files=files) flask.flash("File uploaded succesfully!") else: flask.flash("Format not supported!") return flask.redirect(flask.url_for("uploader"))
def __init__(self): self.conn = get_db_connection()
out = { "get_restaurants": { "result": result, "status":"success" } } if out['get_restaurants']['status'] == 'fail': self.set_status(400) self.finish(out) else: self.write(json.dumps(out)) self.finish() configuraion = utils.read_from_configuration('config.yaml') db = utils.get_db_connection(configuraion) application = tornado.web.Application([ (r"/", MainHandler), (r"/menu", Menu), (r"/team", Team), (r"/employee", Employee), (r"/restaurant", Restaurant), (r"/random_lunch", Random_lunch), (r"/paid_lunch", Paid_lunch), (r"/get_teams", Get_Teams), (r"/get_employees", Get_Employees), (r"/get_restaurants", Get_Restaurants), ], db=db) if __name__ == "__main__":
def index_code_snippet(writer): mysql_conn = utils.get_db_connection() stmt = mysql_conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) querySO = """ SELECT Q.Id as QId, Q.Title, Q.Body as QBody, Q.Tags, Q.ViewCount, Q.Score, A.Body as ABody, A.Id as AId FROM posts as Q JOIN posts as A ON Q.Id = A.ParentId WHERE A.AcceptedAnswer = 1 AND A.Score > 0 AND A.Body LIKE "%</code>%" AND LOWER(Q.Title) NOT LIKE "%not%" AND LOWER(Q.Title) NOT LIKE "%why%" AND LOWER(Q.Title) NOT LIKE "%error%" AND LOWER(Q.Title) NOT LIKE "%no %" AND LOWER(Q.Title) NOT LIKE "% install%" AND LOWER(Q.Title) NOT LIKE "% can't%" AND LOWER(Q.Title) NOT LIKE "% don't%" AND LOWER(Q.Title) NOT LIKE "% issue%" AND LOWER(Q.Title) NOT LIKE "difference %" AND LOWER(Q.Title) NOT LIKE "unable %" AND LOWER(Q.Title) NOT LIKE "debug %" AND LOWER(Q.Title) NOT LIKE "exception %" AND LOWER(Q.Title) NOT LIKE "best way %" """ # Returns nearly 400.000 posts #AND Q.CreationDate < "2014-01-01 00:00:00" #AND A.CreationDate < "2013-06-01 00:00:00" stmt.setFetchSize(Integer.MIN_VALUE) rs = stmt.executeQuery(querySO) i = 0 not_indexed = [] failed_id_gen = load_so_fail_ids() failed_id = next(failed_id_gen, None) while rs.next(): i += 1 if i % 1000 == 0: print "C: %s" % (i) #print "hallo" question_id = rs.getInt("QId") answer_id = rs.getInt("AId") title = rs.getString("Title") #question_body = SOParser.clean_question(utils.unescape_html(rs.getString("QBody"))) # tags = rs.getString("Tags").replace("><", " ").replace("<","").replace(">","") view_count = rs.getString("ViewCount") score = rs.getInt("Score") qbody = utils.so_text(rs.getString("QBody")) abody = rs.getString("ABody") #abodytext = utils.so_text((rs.getString("ABody"))) #print question_id, failed_id if question_id == failed_id: # Get next failed id failed_id = next(failed_id_gen, None) #print "Omit question: %s" % failed_id continue document = Document() document.add( StringField("id", String.valueOf(question_id), Field.Store.YES)) document.add( StringField("answer_id", String.valueOf(answer_id), Field.Store.YES)) document.add( Field("title", title, Field.Store.YES, Field.Index.ANALYZED)) p = PostParser(abody) document.add( StringField("description", p.first_description(), Field.Store.YES)) # document.add(Field("qbody", qbody, Field.Store.YES, Field.Index.ANALYZED)) # document.add(Field("abody", abodytext, Field.Store.YES, Field.Index.ANALYZED )) # for tag in tags.split(): # if tag: # document.add(Field("tags", tag, Field.Store.YES, Field.Index.ANALYZED )) document.add( Field("view_count", view_count, Field.Store.YES, Field.Index.ANALYZED)) if add_code_into_document(document, abody): #add_code_from_mongo(document, coll, answer_id) writer.addDocument(document) else: #print "Not Indexed: %s" % question_id not_indexed.append(question_id) #parse java code print "Not Index: %s" % len(not_indexed)
def book_transport(transport_id, person_id, count_of_persons): # noqa: E501 """booking_transport :param transportId: :type transportId: int :param personId: :type personId: int :param countOfPersons: :type countOfPersons: int :rtype: dict """ LOGGER.info('booking starts!!!!') # sql = 'select "Id" from "Sits" ' \ # 'where "Transport_Id" = %s and "State" = 1' sql = 'select "Price" from "Routes" where "Transport_Id" = %s' sql_get_price = 'select "Price" from "Routes" where "Id" = %s' try: with get_db_connection() as connection: with connection.cursor() as cursor: # cursor.execute(sql, (transport_id,)) # sits_data = cursor.fetchall() # if not sits_data or len(sits_data) < count_of_persons: # return 'No available sits' cursor.execute(sql_get_price, (transport_id, )) price = cursor.fetchone() if not price: LOGGER.error('no transport') return None else: price = price[0] except: LOGGER.error(traceback.format_exc()) print(traceback.format_exc()) return None # LOGGER.info('count of available sits: {}'.format(len(sits_data))) # # sits_id_available = [x[0] for x in sits_data] # sits_to_book = sits_id_available[:count_of_persons] # sql_insert_booking = 'insert into "Booking_Info"("Person_Id", "Transport_Id", "Count_Of_Persons", "Price") ' \ 'values (%s, %s, %s, %s)' sql_select_booking_id = 'select "Id" from "Booking_Info" ' \ 'where "Person_Id" = %s and "Transport_Id" = %s' try: with get_db_connection() as connection: with connection.cursor() as cursor: cursor.execute(sql_insert_booking, (person_id, transport_id, count_of_persons, price * count_of_persons)) cursor.commit() cursor.execute(sql_select_booking_id, (person_id, transport_id)) booking_id = cursor.fetchone()[0] except: LOGGER.error(traceback.format_exc()) print(traceback.format_exc()) booking_id = 100 # # sql = 'update "Sits" ' \ # 'set "State" = 2, "Booking_Id" = %s where "Id" = %s ' # for i in range(count_of_persons - 1): # sql += 'or "Id" = %s ' # query_params = [booking_id] + sits_to_book # try: # with get_db_connection() as connection: # with connection.cursor() as cursor: # cursor.execute(sql, query_params) # except: # LOGGER.error(traceback.format_exc()) # print(traceback.format_exc()) # return 'Booking failed' return {'bookingId': booking_id}
def __init__(self): self.conn = get_db_connection() self.query = '''INSERT INTO book (title, pages, author_id) VALUES("{}", "{}", "{}")'''
Args: term (str): The search term to query. location (str): The location of the business to query. """ response = search(term, location) businesses = response.get('businesses') if not businesses: print u'No businesses for {0} in {1} found.'.format(term, location) return return businesses if __name__ == "__main__": connection = get_db_connection('brick') restaurants = get_db_collection('restaurants') ny_food_response = query_api('food', 'new+york') sf_food_response = query_api('food', 'san+francisco') food_responses = ny_food_response + sf_food_response for entry in food_responses: location = entry['location'] address = location['address'][0] + ' ' + location['city'] + ', ' + location['state_code'] + ' ' + location['postal_code'] url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + to_url_param(address) + '&key=' + GOOGLE_API_KEY response = json.loads(urllib2.urlopen(url).read()) location = response['results'][0]['geometry']['location'] latitude = location['lat'] longitude = location['lng'] categories = [] for category in entry['categories']:
def get_price_by_days(departure_date, start_point, end_points, transport_type, count_of_persons): # start_city_name = start_point id_to_name = {1: 'челябинск', 2: 'москва', 3: 'милан', 4: 'берлин', 5: 'рим', 6: 'сочи', 0: 'казань'} # try: # resp = http.request('GET', URL_CITY + 'cities/{}'.format(start_point)) # LOGGER.info(resp.data) # # start_city = json.loads(resp.data.decode('utf-8')).replace('\'', '"') # # LOGGER.info(data) # # data2 = json.loads(data) # # data2 = json.loads(data) # # print(data2['CityName'].lower()) # start_city = json.loads(start_city) # if start_city: # start_city_name = start_city['CityName'].lower() # else: # LOGGER.error('no city with such id') # return None # except: # LOGGER.error(traceback.format_exc()) # return None # end_city_names = {} # for point in end_points: # try: # res = http.request('GET', URL_CITY + 'cities/{}'.format(point)) # end_city = json.loads(res.data.decode('utf-8')).replace('\'', '"') # end_city = json.loads(end_city) # if end_city: # end_city_names[end_city['CityName'].lower()] = point # else: # LOGGER.error('no city with such id') # return None # except: # LOGGER.error(traceback.format_exc()) # return None # end_city_names = {} # for c in end_points: # end_city_names[c] = c start_city_name = id_to_name[start_point] end_city_names = {} for i in end_points: end_city_names[id_to_name[i]] = i sql_select_start_point = 'select "Id" from "Cities" ' \ 'where lower("Name") = %s' sql_select_end_points = 'select "Id", lower("Name") from "Cities" ' \ 'where lower("Name") = %s ' for i in range(len(end_city_names) - 1): sql_select_end_points += 'or lower("Name") = %s ' with get_db_connection() as connection: with connection.cursor() as cursor: cursor.execute(sql_select_start_point, (start_city_name,)) start_point_id = cursor.fetchone()[0] if not start_point: LOGGER.error('No such city in db') return None cursor.execute(sql_select_end_points, [k for k in end_city_names.keys()]) end_points_data = cursor.fetchall() if not end_points_data: LOGGER.error('No such cities in db') print(start_point_id, end_points_data) sql_get_routes_by_end_point = 'select "Routes"."Id", "Routes"."Name", ' \ '"Departure_Time", "Arrive_Time", "Price" ' \ 'from "Routes", "Types" ' \ 'where "Start_Point" = %s and "End_Point" = %s ' \ 'and "Types"."Id" = "Routes"."Transport_Type" ' \ 'and "Departure_Time"::date >= %s and "Departure_Time"::date <= %s ' \ 'and "Types"."Name" = %s and "Price" = (' \ 'select min("Price") from "Routes", "Types" ' \ 'where "Start_Point" = %s and "End_Point" = %s ' \ 'and "Types"."Id" = "Routes"."Transport_Type" ' \ 'and "Departure_Time"::date >= %s and "Departure_Time"::date <= %s ' \ 'and "Types"."Name" = %s)' routes_resp = [] with get_db_connection() as connection: with connection.cursor() as cursor: for p in end_points_data: for t_type in transport_type: query_params = [start_point_id, p[0], departure_date, departure_date, t_type] cursor.execute(sql_get_routes_by_end_point, query_params + query_params) route_data = cursor.fetchone() if route_data: routes_resp.append(Route(transport_id=route_data[0], transport_type=t_type, name=route_data[1], start_point=start_point, end_point=end_city_names[p[1]], departure_time=int(route_data[2].timestamp()), arrive_time=int(route_data[3].timestamp()), price=route_data[4], sits=None).to_dict()) else: routes_resp.append(Route(transport_id=-1, start_point=start_point, end_point=end_city_names[p[1]], transport_type=t_type).to_dict()) return routes_resp
def get_transport_by_id(transport_id): """Find transport by ID Returns a single transport # noqa: E501 :param transportId: ID of transport :type transportId: int :rtype: Route """ sql_get_transport = 'select "Routes"."Id", "Types"."Name", "Routes"."Name", ' \ '"Start_Point", "End_Point", "Departure_Time", "Arrive_Time", "Price" ' \ 'from "Routes", "Types" ' \ 'where "Routes"."Id" = %s and "Routes"."Transport_Type" = "Types"."Id";' sql_get_cities = 'select lower("Name") from "Cities" where "Id" = %s or "Id" = %s' sql_get_sits = 'select "Transport_Id", "State", "Sit_Number" ' \ 'from "Sits" where "Transport_Id" = %s' try: with get_db_connection() as connecton: with connecton.cursor() as cursor: cursor.execute(sql_get_transport, (transport_id,)) route_data = cursor.fetchone() if not route_data: LOGGER.error('Route not found') return None cursor.execute(sql_get_cities, (route_data[3], route_data[4])) cities = cursor.fetchall() if not cities or len(cities) < 2: LOGGER.error('Cities not found') return None cursor.execute(sql_get_sits, (transport_id,)) sits = cursor.fetchall() if not sits: LOGGER.error('Sits not found') return None except: LOGGER.error(traceback.format_exc()) return None start_city = cities[0][0] end_city = cities[0][0] start_point = route_data[3] end_point = route_data[4] try: resp = http.request('POST', URL_CITY + 'cityitem', body=json.dumps({'Name': start_city.title()}), headers={'Content-type': 'application/json'}) data = json.loads(resp.data) # data2 = json.loads(data) start_city = json.loads(data) if start_city and isinstance(start_city, list): start_point = start_city[0]['cityId'] else: raise Exception resp = http.request('POST', URL_CITY + 'cityitem', body=json.dumps({'Name': end_city.title()}), headers={'Content-type': 'application/json'}) data = json.loads(resp.data) end_city = json.loads(data) if end_city and isinstance(end_city, list): end_point = end_city[0]['cityId'] else: raise Exception except: LOGGER.error(traceback.format_exc()) return None sits_list = [] for sit in sits: sits_list.append(Sit(state=sit[1], sit_number=sit[2])) route = Route(transport_id=transport_id, transport_type=route_data[1], name=route_data[2], start_point=start_point, end_point=end_point, departure_time=int(route_data[5].timestamp()), arrive_time=int(route_data[6].timestamp()), price=route_data[7], sits=sits_list) return route.to_dict()
def __init__(self): self.conn = get_db_connection() self.query = '''INSERT INTO author (first_name, last_name) VALUES("{}", "{}")'''
import requests import json import psycopg2 import time from utils import get_db_connection api_base_url = "https://cdn-api.co-vin.in/api" conn = get_db_connection() def main(): start_t = time.time() print("Accessing API at {}".format(api_base_url)) clear_db() states = get_states()['states'] get_districts(states) conn.close() end_t = time.time() print("Time taken to get districts: {:.2f}s".format(end_t - start_t)) def clear_db(): cur = conn.cursor() # execute a statement print('Clearing states in db') cur.execute('DELETE from public.states') # close the communication with the PostgreSQL
Args: term (str): The search term to query. location (str): The location of the business to query. """ response = search(term, location) businesses = response.get('businesses') if not businesses: print u'No businesses for {0} in {1} found.'.format(term, location) return return businesses if __name__ == "__main__": connection = get_db_connection('brick') restaurants = get_db_collection('restaurants') ny_food_response = query_api('food', 'new+york') sf_food_response = query_api('food', 'san+francisco') food_responses = ny_food_response + sf_food_response for entry in food_responses: location = entry['location'] address = location['address'][0] + ' ' + location[ 'city'] + ', ' + location['state_code'] + ' ' + location[ 'postal_code'] url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + to_url_param( address) + '&key=' + GOOGLE_API_KEY response = json.loads(urllib2.urlopen(url).read()) location = response['results'][0]['geometry']['location'] latitude = location['lat'] longitude = location['lng']