def post(self): cursor = db.cursor() data = self.assure_input_valid() if not data: return username, pwd, email = data hash_pwd = hash_password(pwd) cursor.execute(""" INSERT INTO `yagra`.`yagra_user` ( `user_login`, `user_passwd`, `display_name`, `user_email`, `user_register`, `user_status`) VALUES (%s, %s, %s, %s, %s, %s) """, (username, hash_pwd, username, email, time.strftime('%Y-%m-%d %H:%M:%S'), str(1))) db.commit() # self.write("Username: %s registered success!" % escape(username)) self.redirect("/accounts/login")
def users_post(): try: email = flask.request.form['email'] password = flask.request.form['password'] name = flask.request.form['name'] except: return flask.abort(400) hash = md5((email+'salt'+password).encode('utf-8')).hexdigest() id = md5((email+'salt').encode("utf-8")).hexdigest() q = "SELECT id FROM users WHER id = '" + id + "'" r = db.exec_query(q).fetchone() if len(r) > 0: return json.dumps({'reason': 'Wrong login or password'}), 403 q = "INSERT INTO users VALUES ('{}', '{}', '{}', '{}', '{}', '{}')".format( id, hash, email, name, '', '' ) db.exec_query(q) db.commit() return json.dumps({'reason':'Registration complete'}), 201
def post(self): user_head = self.get_argument("user_head") csrf_token = self.get_argument("csrf_token") if csrf_token != self.session["_csrf_token"]: self.set_status(403) return username = self.session["username"] upload_filename = unicode(self.request.files["user_head"].filename, encoding="utf-8") filename = create_random_filename(username + "_" + upload_filename) full_filename = "uploads/" + filename logging.info("Writing file to %s" % (filename, )) with open(full_filename, "wb") as out: out.write(user_head) # 检查用户是否存在 cursor = db.cursor() cursor.execute(""" SELECT ID, user_email FROM yagra_user WHERE user_login = %s""", (username, )) row = cursor.fetchone() if row: user_id, user_email = row m = hashlib.md5() m.update(user_email) email_md5 = m.hexdigest() # 插入图片信息到数据库中 cursor.execute(""" INSERT INTO yagra_image (user_id, filename, upload_date) VALUES (%s, %s, %s)""", (str(user_id), filename, time.strftime('%Y-%m-%d %H:%M:%S'))) image_id = cursor.lastrowid # 判断用户是否已经有默认头像,没有则设置默认头像 cursor.execute(""" SELECT * FROM yagra_user_head WHERE user_email_md5 = %s""", (email_md5, )) row = cursor.fetchone() if not row: logging.info("Insert into db. Filename %s, " "image_id: %d, " "user_id: %d" % (filename, image_id, user_id)) cursor.execute(""" INSERT INTO yagra_user_head (user_id, image_id, user_email_md5) VALUES (%s, %s, %s)""", (user_id, image_id, email_md5)) db.commit() self.redirect("/user")
def account_update_languages(): form = UpdateLanguages() if form.validate_on_submit(): languages = request.form.get('languages') db.update_languages(current_user.id, languages) db.commit() flash('Your account has been updated!', 'success') return redirect(url_for('account')) return render_template('account_update_languages.html', form=form)
def account_update_about(): form = UpdateAbout() if form.validate_on_submit(): about = request.form.get('about') db.update_about(current_user.id, about) db.commit() flash('Your account has been updated!', 'success') return redirect(url_for('account')) return render_template('account_update_about.html', form=form)
async def on_command_error(self, ctx, error): # print(db.get_cooldown()) if ctx.author.id in db.get_cooldown(): return elif isinstance(error, commands.CommandOnCooldown): m, s = divmod(error.retry_after, 60) await ctx.send(embed=discord.Embed( description= f"This command is currently **on cooldown** for ,Please **try again in** `{'%02d seconds' % (s,)}`.", color=discord.Colour.red()), delete_after=2) db.cr.execute("INSERT OR IGNORE INTO cooldown(user_id) VALUES(?)", (ctx.author.id, )) db.commit() return elif isinstance(ctx.channel, discord.channel.DMChannel): return elif isinstance(error, commands.errors.MemberNotFound): embed = member_not_found_en() if db.get_lang(ctx) == "ar": embed = member_not_found_ar() await ctx.send(embed=embed) return elif isinstance(error, commands.MissingRequiredArgument): aliases = [] if ctx.command.aliases == []: aliases = None else: aliases = ", ".join(ctx.command.aliases) embed = discord.Embed( description=f"**command:** {ctx.command.name}\n\ **help:** {ctx.command.help}\n\ **used:** {db.get_prefix(ctx)}{ctx.command.usage}\n\ **aliases:** {aliases}\n", color=Colour.red()).set_author(name=ctx.command.cog_name) await ctx.send(embed=embed) return elif isinstance(error, commands.errors.BadArgument): aliases = [] if ctx.command.aliases == []: aliases = None else: aliases = ", ".join(ctx.command.aliases) embed = discord.Embed( description=f"**command:** {ctx.command.name}\n\ **help:** {ctx.command.help}\n\ **used:** {db.get_prefix(ctx)}{ctx.command.usage}\n\ **aliases:** {aliases}\n", color=Colour.red()).set_author(name=ctx.command.cog_name) await ctx.send(embed=embed) return elif isinstance(error, commands.errors.MissingPermissions): await ctx.send(error) else: pass
def get_chapter(link, content_path, title_path, book): res = requests.get(link) res.encoding = _encoding d = pq(res.text) # 爬取内容并格式化 content = format(d(content_path).html()) title = d(title_path).text() Chapter(link=link, title=title, content=content, book=book) # 令人惊奇的是LongStr的章节内容需要commit,应该吧 db.commit()
def store_working_commit(repo_id, commit): # Store the working commit. store_commit = ("UPDATE repos " "SET working_commit = %s " "WHERE id = %s") cursor.execute(store_commit, (commit, repo_id)) db.commit() log_activity('Debug', 'Stored working commit: %s' % commit)
def account_change_number(): form = ChangeNumber() if form.validate_on_submit(): phone_number = request.form.get('phone_number') print(phone_number) db.update_phone_number(current_user.id, phone_number) db.commit() flash('Your Phone number has been updated', 'success') return redirect(url_for('account_info')) return render_template('account_change_number.html', form=form)
def save_masto_token(self, access_token, instance): db.execute( """SELECT id FROM mastodon_instances WHERE instance = ?;""", (instance, )) instance_id = db.cur.fetchone()[0] db.execute( "INSERT INTO mastodon_accounts(user_id, access_token, instance_id, active) " "VALUES(?, ?, ?, ?);", (self.uid, access_token, instance_id, 1)) db.commit()
def init_lifts(resort_id): parsed_json = parse(resort_id) lifts = parsed_json['Lifts'] lift_names = list(map(lambda l: l['Name'], lifts)) #save lift names in db for lift in lift_names: sql = 'INSERT INTO lifts (resort_id, name) VALUES (%s, %s)' val = (resort_id, lift) db.execute(sql, val) db.commit() db.close_db_connection()
def assign_employee_to_property(): try: if (current_user.title == "Branch Manager"): assign_map = {} form = AssignEmployeeToProperty() if form.validate_on_submit(): assign_map['employeeusername'] = request.form.get( 'employeeusername') assign_map['propertyname'] = request.form.get('propertyname') #ensure employee and property are from this branch manager's branch (country) db.get_property_country(assign_map['propertyname']) property_country = db.fetch_one() db.get_employee_country(assign_map['employeeusername']) employee_country = db.fetch_one() if employee_country == None: raise Exception("This user is not an employee!") if property_country == None: raise Exception("This property is not part of your branch") property_country = property_country[0] employee_country = employee_country[0] if (current_user.country != property_country): raise Exception( "This property is not part of your branch!") if (current_user.country != employee_country): raise Exception( "This employee is not part of your branch!") db.assign_employee_to_property(assign_map['employeeusername'], assign_map['propertyname']) db.commit() flash( 'Success! ' + assign_map['employeeusername'] + ' has been assigned to the property ' + assign_map['propertyname'], 'success') return render_template('assign_employee_to_property.html', form=form) else: abort(404) except Exception as e: db.close() db.new_connection() print(e) flash('Error: ' + str(e), 'danger') return render_template('assign_employee_to_property.html', form=form) return render_template('assign_employee_to_property.html', form=form)
def log_activity(level, status): # Log an activity based upon urgency and user's preference log_options = ('Error', 'Quiet', 'Info', 'Verbose', 'Debug') if log_options.index(level) <= log_options.index(log_level): query = ("INSERT INTO utility_log (level,status) VALUES (%s,%s)") cursor.execute(query, (level, status)) db.commit() sys.stderr.write("* %s\n" % status)
def update_affiliation(email_type, email, affiliation, start_date): update = ("UPDATE analysis_data " "SET %s_affiliation = %%s " "WHERE %s_email = %%s " "AND %s_affiliation IS NULL " "AND %s_date >= %%s" % (email_type, email_type, email_type, email_type)) cursor.execute(update, (affiliation, email, start_date)) db.commit()
def ban_roadblock_author(bot, query): if query.message.chat.id == mods_chat: nmaps_message = retrieve_roadblock(mods_id=query.message.message_id) else: nmaps_message = retrieve_roadblock(roads_id=query.message.message_id) query.edit_message_text(BOT_USER_BANNED.format(user_name(query.from_user), query.from_user.id), parse_mode='markdown') c = db.cursor() c.execute('INSERT INTO banned VALUES(%s)', (nmaps_message['user_id'], )) db.commit() c.close()
def trim_commit(repo_id, commit): # Quickly remove a given commit remove_commit = ("DELETE FROM analysis_data " "WHERE repos_id=%s " "AND commit=%s") cursor.execute(remove_commit, (repo_id, commit)) db.commit() log_activity('Debug', 'Trimmed commit: %s' % commit)
def del_comment(id): """ Deletes the <<Comment>> object given its id from the database """ from db import db, Comment comment = get_comment(id) db.session.delete(comment) db.commit() delete_notifications_w_relevance("new_comment", id)
def on_get(self, req, resp): '''Return json object related to GET with lat & lon HTTP parameters ''' raw_lat = req.get_param('lat') raw_lon = req.get_param('lon') if raw_lat is None or raw_lon is None: resp.status = falcon.HTTP_400 lat = None lon = None else: lat = decimal.Decimal(raw_lat) lon = decimal.Decimal(raw_lon) if not (self.lat_is_valid(lat) and self.lon_is_valid(lon)): resp.status = falcon.HTTP_400 else: cur = db.cursor() nb_maps_raw = req.get_param('nb_maps') nb_addr_raw = req.get_param('nb_addr') if nb_maps_raw is None: nb_maps_raw = '20' if nb_addr_raw is None: nb_addr_raw = '10' nb_maps = decimal.Decimal(nb_maps_raw) nb_addr = decimal.Decimal(nb_addr_raw) #id (uuid), path (str), geom (geom), address (str), level (str), building (str) loc = "st_setsrid(st_makepoint(%s,%s),4326)" % (lon,lat) query = "SELECT array_to_json(array_agg(row_to_json(t)))::text FROM (" query += " SELECT floor(st_distance(geom::geography, %s::geography)) as dist, " % loc query += " ST_X(geom) as lon, ST_Y(geom) as lat, * FROM ((select * from ban_nomap where ST_DWithin(geom, %s, 0.001) order by st_distance(geom,%s) limit %s) union (select * from map_info where ST_DWithin(geom, %s, 0.1) limit %s)) as d ORDER BY ST_Distance(geom,%s), level" % ( loc,loc,adapt(nb_addr),loc,adapt(nb_maps),loc) query += " ) t" cur.execute(query) what_is_around = cur.fetchone()[0] resp.set_header('X-Powered-By', 'OpenEvacMap') if what_is_around is None: resp.status = falcon.HTTP_204 else: resp.status = falcon.HTTP_200 resp.set_header('Access-Control-Allow-Origin', '*') resp.set_header('Access-Control-Allow-Headers', 'X-Requested-With') resp.body = (what_is_around) query = """INSERT INTO log (loc, ip) VALUES (ST_SetSRID(ST_GeometryFromText('POINT(%s %s)'),4326),'%s');""" % (lon,lat,req.env['REMOTE_ADDR']) cur.execute(query) db.commit() cur.close()
def init_lifts(resort_id): lifts_dom = parse(resort_id) lifts = lifts_dom.find_all('div','lift') lift_names = list(map(lambda l: l.find_all('div','cell')[0].text, lifts)) #save lift names in db for lift in lift_names: sql = 'INSERT INTO lifts (resort_id, name) VALUES (%s, %s)' val = (resort_id, lift) db.execute(sql, val) db.commit() db.close_db_connection()
def add(args): name = args.get("name") model = args.get("model", "normal") userid = args.get("userid") if not userid: raise InvalidUser id = maxid() + 1 if not name: name = str(id) sql = "INSERT INTO node(id, name, model, userid)VALUES(?, ?, ?, ?)" db.execute(sql, (id, name, model, userid)) db.commit()
def get_weather_for_resort(resort_id): apikey = config['appid'] res = db.query('SELECT geo_lat, geo_lon FROM resorts WHERE id='+str(resort_id)) latitude = res[0]['geo_lat'] longitude = res[0]['geo_lon'] url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&APPID={}'.format(latitude, longitude, apikey) report = requests.get(url) weather_data = json.loads(report.content) data_map = { 'source': 'openweathermap', 'updated_at': time.strftime('%Y-%m-%d %H:%M:%S'), 'resort_id': resort_id } if len(weather_data) > 0: if len(weather_data['weather']) > 0: weather = weather_data['weather'][0] if 'id' in weather: data_map['label_id'] = weather['id'] if 'main' in weather: data_map['label'] = weather['main'] if 'description' in weather: data_map['description'] = weather['description'] if 'main' in weather_data: main = weather_data['main'] if 'temp' in main: data_map['temperature'] = (main['temp'] - 273.15) #kelvin->centigrade if 'pressure' in main: data_map['pressure'] = main['pressure'] if 'humidity' in main: data_map['humidity'] = main['humidity'] if 'temp_min' in main: data_map['temperature_min'] = (main['temp_min'] - 273.15) #kelvin->centigrade if 'temp_max' in main: data_map['temperature_max'] = (main['temp_max'] - 273.15) #kelvin->centigrade if 'visibility' in weather_data: data_map['visibility'] = weather_data['visibility'] if 'wind' in weather_data: wind = weather_data['wind'] if 'speed' in wind: data_map['wind_speed'] = wind['speed'] if 'deg' in wind: data_map['wind_dir'] = wind['deg'] if 'clouds' in weather_data and 'all' in weather_data['clouds']: data_map['cloudiness'] = weather_data['clouds']['all'] if 'rain' in weather_data: rain = weather_data['rain'] if '1h' in rain: data_map['rain_last_1h'] = rain['1h'] if '3h' in rain: data_map['rain_last_3h'] = rain['3h'] if 'snow' in weather_data: snow = weather_data['snow'] if '1h' in snow: data_map['snow_last_1h'] = snow['1h'] if '3h' in snow: data_map['snow_last_3h'] = snow['3h'] if 'dt' in weather_data: data_map['data_calculated_at'] = datetime.utcfromtimestamp(weather_data['dt']).strftime('%Y-%m-%d %H:%M:%S') cols = ','.join(data_map.keys()) vals = data_map.values() vals = tuple(vals) tmp = ','.join(['%s'] * len(vals)) sql = 'INSERT INTO weather_reports ({}) VALUES ({})'.format(cols,tmp) db.execute(sql, vals) db.commit() db.close_db_connection()
def store_working_author(email): # Store the working author during affiliation discovery, in case it is # interrupted and needs to be trimmed. store = ("UPDATE settings " "SET value = %s " "WHERE setting = 'working_author'") cursor.execute(store, (email, )) db.commit() log_activity('Debug', 'Stored working author: %s' % email)
def account(): form = AccountPicture() if form.validate_on_submit(): picture_file = save_picture(form.picture.data) current_user.picture = picture_file db.update_picture(current_user.id, picture_file) db.commit() flash('Your account has been updated', 'success') picture = url_for('static', filename='images/' + current_user.picture) return render_template('account.html', title='Account', form=form, picture=picture)
def get_all_data(): """ Function get all weather data for all weather stations from csv file from start date of observations to today or update data from date of last getting weather.""" global current_session wanted_stations = weather_csv.read_new_cities(STATIC_ROOT, DELIMITER) if wanted_stations: station: classes.WeatherStation for station in wanted_stations: current_session = Session() if station.start_date is None or station.number is None: rp5_parser.get_missing_ws_info(current_session, SAVE_IN_DB, station) print(f"Start getting data for {station.city} city with " f"start date of observations {station.start_date}...") else: print( f"Start getting data for {station.city} city with last " f"date of loading {station.start_date.strftime('%Y.%m.%d')} ..." ) create_directory(station) start_year: int = station.start_date.year if SAVE_IN_DB: country_id = db.executesql( queries.get_country_id(station.country))[0][0] city_id = db.executesql( queries.get_city_id(station.city, country_id))[0][0] station.ws_id = db.executesql( queries.get_ws_id(station, city_id, country_id))[0][0] db.commit() flag = True while start_year < datetime.now().year + 1: if start_year == station.start_date.year: start_date: date = station.start_date else: start_date: date = date(start_year, 1, 1) flag = get_weather_for_year(start_date, station.number, station.ws_id) start_year += 1 station.start_date = datetime.now().date() - timedelta(days=1) if flag: print("Data was loaded!") current_session.close() weather_csv.update_csv_file(STATIC_ROOT, DELIMITER, wanted_stations) return
def add(args): username = args.get("username", None) password = args.get("password", None) if username and len(username) > 0 and password and len(password) > 0: if checkExist(username): raise AccountExist maxId = fetchMaxId() + 1 sql = "INSERT INTO account (id, username, password)VALUES(?, ?, ?)" db.execute(sql, (maxId, username, password)) db.commit() return Account(maxId) else: raise InvalidArgument
def create_user_table(wallet_userid): cur = db.cursor() cur.execute(""" create table users( wallet varchar(34) primary key, userid int ); """) execute_values(cur, "insert into users (wallet, userid) values %s", wallet_userid.items()) db.commit() cur.close()
def add_payout_method(): payout_method = {} form = PayoutMethod() if form.validate_on_submit(): payout_method['username'] = current_user.id payout_method['paypal_address'] = request.form.get('paypal_address') db.create_payout_method(payout_method['username'], payout_method['paypal_address']) flash(f'Payout method created!', 'success') db.commit() return redirect(url_for('your_payout_method')) return render_template('add_payout_method.html', title='Add Payout Method', form=form)
def saveUserDetails(self): username = self.txt_username.toPlainText() new_password = self.txt_newPassword.toPlainText() old_password = self.txt_oldPassword.toPlainText() url = self.txt_url.toPlainText() cursor = db.cursor() cursor.execute( '''INSERT INTO databasecredentials(url, usernname,password) VALUES(?,?,?)''', (url, username, new_password)) db.commit() self.txt_url.setText("") self.txt_username.setText("") self.txt_newPassword.setText("") self.txt_oldPassword.setText("")
def get_request_token(self): db.execute( """SELECT request_token, request_token_secret FROM twitter_request_tokens WHERE user_id = ?;""", (self.uid, )) request_token = db.cur.fetchone() db.execute( """DELETE FROM twitter_request_tokens WHERE user_id = ?;""", (self.uid, )) db.commit() return { "oauth_token": request_token[0], "oauth_token_secret": request_token[1] }
def update_subscription(bot, update): c = db.cursor() if not subscribed(update.message.from_user.id): c.execute('INSERT INTO subscribers VALUES (%s)', (update.message.from_user.id, )) update.message.reply_text(BOT_SUBSCRIBED_USR, reply_markup=get_keyboard(update, True)) else: c.execute('DELETE FROM subscribers WHERE id=(%s)', (update.message.from_user.id, )) update.message.reply_text(BOT_UNSUBSCRIBED_USR, reply_markup=get_keyboard(update, False)) db.commit() c.close()
def on_get(self, req, resp): '''Return JPEG map image according to id param ''' map_id = req.get_param('id') if not self.map_id_is_valid(map_id): resp.status = falcon.HTTP_400 else: cur = db.cursor() #id (uuid), path (str), geom (geom), address (str), level (str), building (str) query = "SELECT path, ST_astext(geom) as geom FROM %s" % self._table query += " WHERE id='%s'" % (map_id) cur.execute(query) cur_map = cur.fetchall() map_path = cur_map[0][0] map_geom = cur_map[0][1] resp.set_header('X-Powered-By', 'OpenEvacMap') if map_path is None: resp.status = falcon.HTTP_404 else: full_path = os.path.join(config.map_dir,map_path) preview = req.get_param('preview') if preview is None: preview = '0' if preview=='1': outfile = os.path.splitext(full_path)[0] + "_preview.jpg" print(outfile) if os.path.exists(outfile)==False: im = Image.open(full_path) im.thumbnail(preview_size, Image.ANTIALIAS) im.save(outfile, "JPEG") full_path=outfile resp.status = falcon.HTTP_200 resp.set_header('Access-Control-Allow-Origin', '*') resp.set_header('Access-Control-Allow-Headers', 'X-Requested-With') resp.set_header("Content-Type", "image/jpeg") resp.set_header("Content-Length", "%s" % os.path.getsize( full_path)) with open(full_path, "rb") as f: resp.body = f.read() query = """INSERT INTO log (loc, ip, map) VALUES (ST_GeometryFromText('%s'),'%s','%s');""" % (map_geom,req.env['REMOTE_ADDR'],map_id) cur.execute(query) db.commit() cur.close()
def post(self): current_id = get_jwt_identity() args = parser.parse_args() if args["college"] != "" and args["major"] != "": with db.cursor(DictCursor) as cursor: sql = "INSERT INTO `educations` (`college`, `major`, `degree`, `user_id`) VALUES (%s, %s, %s, %s)" cursor.execute( sql, (args["college"], args["major"], args["degree"], current_id), ) db.commit() return jsonify(status="success") return jsonify(status="fail")
def insert_team_players(rows, team_id, year): for row in rows: names = row[3].split(' ') first = names[0] last = ' '.join(names[1:]) query = 'INSERT IGNORE INTO player (id, first, last, num, position, height, weight, birthday, school) VALUES (%d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")' values = (row[12], first, last, row[4], row[5], row[6], row[7], row[8], row[11]) cur.execute(query % values) db.commit() query = "INSERT IGNORE INTO player_team_rel (player_id, team_id, year) VALUES (%d, %d, %d)" values = (row[12], team_id, year) cur.execute(query % values) db.commit()
def print_response(response, url): with closing(db.cursor()) as x: for report in response.get('reports', []): for row in report.get('data', {}).get('rows', []): dateRangeValues = row.get('metrics', []) for value in dateRangeValues: val = (value.get('values')) x.execute( """UPDATE search_console_data SET nusers = (%s), user_check = 1 WHERE url = (%s) AND date = (%s)""", (val, url, my_date)) x.execute( """INSERT INTO ga_urls (ganusers, gaurl, gadate) VALUES (%s, %s, %s)""", (val, url, my_date)) db.commit()
def get_assets(codes=["USD"]): """ Run periodically to get data """ for code in codes: producers = Asset(asset=code, bitshares_instance=btsconf.confs['bts']) for feed in producers.feeds: dbBTS = BTSAsset( code, datetime.now(), feed["producer"]["id"], float(repr(feed["settlement_price"]).split(" ")[0]), feed["maximum_short_squeeze_ratio"], feed["maintenance_collateral_ratio"], float(repr(feed["core_exchange_rate"]).split(" ")[0]), feed["date"]) db.add(dbBTS) db.commit()
def post(self): current_id = get_jwt_identity() args = parser.parse_args() error = None if not args["title"]: error = "수상내역은 필수 입력값입니다." if error is None: with db.cursor(DictCursor) as cursor: sql = "INSERT INTO `awards` (`title`, `description`, `user_id`) VALUES (%s, %s, %s)" cursor.execute( sql, (args["title"], args["description"], current_id)) db.commit() return jsonify(status="success") return jsonify(status="fail", result={"message": error})
def get_lift_status(resort_id): global lift_map lift_map_sql = db.query('SELECT id, name FROM lifts WHERE resort_id='+str(resort_id)) for sl in lift_map_sql: lift_map[sl['name']] = int(sl['id']) lifts_dom = parse(resort_id) lifts = lifts_dom.find_all('div','lift') lift_status = list(map(get_lift_status_obj, lifts)) #save lift statuses in db for status in lift_status: sql = 'INSERT INTO lift_status (lift_id, status, updated_at) VALUES (%s, %s, %s)' val = (status['lift_id'], status['lift_status'], time.strftime('%Y-%m-%d %H:%M:%S')) db.execute(sql, val) db.commit() db.close_db_connection()
def __call__(self, environ, start_response): try: request = Request(environ) if settings.DEBUG and request.method == 'GET' and request.path.startswith('/%s/' % settings.STATIC): response = self.serve_static(request) else: if settings.SESSION: session_uri = URI(settings.SESSION) if session_uri.scheme == 'db': store = DBStore(table=session_uri.path) elif session_uri.scheme == 'file': store = FileStore(path=session_uri.path) if request.cookies.get('session_key'): request.session = store.load(request.cookies['session_key'].value) else: request.session = Session() response = self.serve_dynamic(request) if settings.SESSION and request.session.modified: store.store(request.session) if not request.cookies.get('session_key'): response.cookies['session_key'] = request.session.key response.finalize() if settings.DB: db.commit() except Exception, e: if settings.DB: db.rollback() if settings.DEBUG: response = self.serve_debug(request) elif settings._500: response = settings._500(request) else: response = Response(body='500 Internal Server Error',content_type='text/plain',status_code=500) response.finalize()
def on_post(self, req, resp, **kargs): '''Update database according to JSON and give ID back ''' address_id = kargs.get('id') env = req.env env.setdefault('QUERY_STRING', '') form = cgi.FieldStorage(fp=req.stream, environ=env) try: file_item = form['image'] raw_lat_item = form['lat'] raw_lon_item = form['lon'] except KeyError: raw_lat = None raw_lon = None image_file = None else: image_file = file_item.file raw_lat = raw_lat_item.value raw_lon = raw_lon_item.value if raw_lat is None or raw_lon is None or image_file is None: resp.status = falcon.HTTP_400 lat = None lon = None else: lat = decimal.Decimal(raw_lat) lon = decimal.Decimal(raw_lon) if not (self.lat_is_valid(lat) and self.lon_is_valid(lon)): resp.status = falcon.HTTP_400 else: cur = db.cursor() columns = ['geom', 'address'] values = ['st_Setsrid(st_makePoint(%s,%s),4326)' % (lon, lat), "%s" % adapt(address_id)] for param in ('name','building','level'): try: param_item = form[param] except KeyError: pass else: columns.append(param) values.append("%s" % adapt(param_item.value)) insert = "INSERT INTO %s (%s)" % (self._table, ",".join(columns)) insert += " VALUES (%s)" % ",".join(values) insert += " RETURNING *" cur.execute(insert) uuid = cur.fetchone()[0] image_path = os.path.join(config.map_dir, "%s.jpg" % uuid) with open(image_path, "wb") as f: f.write(image_file.read()) cur2 = db.cursor() update = "UPDATE %s" % self._table update += " SET path=%s" % adapt(image_path) update += " WHERE id=%s" % adapt(uuid) cur2.execute(update) db.commit() cur.close() cur2.close() try: redirect_url_item = form['redirectUrl'] redirect_url = redirect_url_item.value #split_result = urllib.parse.urlsplit(redirect_url) #netloc = split_result[1] #if netloc != config.netloc: # raise ValueError("What do you think you are doing Dave?") except: resp.status = falcon.HTTP_200 else: resp.status = falcon.HTTP_302 resp.set_header('Location', redirect_url) resp.set_header('Access-Control-Allow-Origin', '*') resp.set_header('Access-Control-Allow-Headers', 'X-Requested-With')