def dofengtaiguohu_add(): status = '0' if request.method == 'POST': print 'dofengtaiguohu_add method is Post' shoumaixingming = request.form.get('shoumaixingming').encode('utf-8') shoumaishenfenzheng = request.form.get('shoumaishenfenzheng').encode('utf-8') goumaixingming = request.form.get('goumaixingming').encode('utf-8') goumaishenfenzheng = request.form.get('goumaishenfenzheng').encode('utf-8') hetonghao = request.form.get('hetonghao').encode('utf-8') qishuipiaohao = request.form.get('qishuipiaohao').encode('utf-8') guohuzhuanyuan = request.form.get('guohuzhuanyuan').encode('utf-8') guohuzhuanyuandianhua = request.form.get('guohuzhuanyuandianhua').encode('utf-8') yuyueshijian = request.form.get('yuyueshijian').encode('utf-8') shijianduan = request.form.get('shijianduan').encode('utf-8') else: print 'dofengtaiguohu_add method is Get' shoumaixingming = request.args.get('shoumaixingming').encode('utf-8') shoumaishenfenzheng = request.args.get('shoumaishenfenzheng').encode('utf-8') goumaixingming = request.args.get('goumaixingming').encode('utf-8') goumaishenfenzheng = request.args.get('goumaishenfenzheng').encode('utf-8') hetonghao = request.args.get('hetonghao').encode('utf-8') qishuipiaohao = request.args.get('qishuipiaohao').encode('utf-8') guohuzhuanyuan = request.args.get('guohuzhuanyuan').encode('utf-8') guohuzhuanyuandianhua = request.args.get('guohuzhuanyuandianhua').encode('utf-8') yuyueshijian = request.args.get('yuyueshijian').encode('utf-8') shijianduan = request.args.get('shijianduan').encode('utf-8') db.connect_db() db.fengtaiguohu_insert((shoumaixingming, shoumaishenfenzheng, goumaixingming, goumaishenfenzheng, hetonghao, qishuipiaohao, guohuzhuanyuan, guohuzhuanyuandianhua, yuyueshijian, shijianduan, status)) return render_template('index.html')
def dodongchengjiaoshui_add(): hetonghao = None kehuxingming = None shenfenzheng = None guohuzhuanyuan = None status = '0' if request.method == 'POST': print 'dodongchengjiaoshui_add method is Post' hetonghao = request.form.get('hetonghao').encode('utf-8') print 'hetonghao:' + hetonghao kehuxingming = request.form.get('kehuxingming').encode('utf-8') shenfenzheng = request.form.get('shenfenzheng').encode('utf-8') guohuzhuanyuan = request.form.get('guohuzhuanyuan').encode('utf-8') yuyueshijian = request.form.get('yuyueshijian').encode('utf-8') shijianduan = request.form.get('shijianduan').encode('utf-8') else: print 'dodongchengjiaoshui_add method is Get' hetonghao = request.args.get('hetonghao').encode('utf-8') kehuxingming = request.args.get('kehuxingming').encode('utf-8') shenfenzheng = request.args.get('shenfenzheng').encode('utf-8') guohuzhuanyuan = request.args.get('guohuzhuanyuan').encode('utf-8') yuyueshijian = request.args.get('yuyueshijian').encode('utf-8') shijianduan = request.args.get('shijianduan').encode('utf-8') db.connect_db() db.dongchengjiaoshui_insert((hetonghao, kehuxingming, shenfenzheng, guohuzhuanyuan, yuyueshijian, shijianduan, status)) return render_template('index.html')
def handler(): payload = json.loads(request.form["payload"]) if "actions" not in payload or "value" not in payload["actions"][0]: return "" action = payload["actions"][0]["value"] user_id = payload["user"]["id"] if action == "activate": requests.post( payload["response_url"], json={ "text": ":robot_face: Activated! While we can't update your previous message (:crying_cat_face:), all your future messages will be made awesome!", "replace_original": "true", }, ) elif action == "maybe_later": requests.post( payload["response_url"], json={ "text": "Alright, I'll ask you again later. Or visit slack.apps.cs61a.org to activate this bot manually!!", "replace_original": "true", }, ) elif action == "never_ask_again": with connect_db() as db: db("INSERT INTO silenced_users VALUES (%s)", (user_id,)) requests.post( payload["response_url"], json={ "text": "Understood. If you ever change your mind, visit slack.apps.cs61a.org to activate this bot!", "replace_original": "true", }, ) return ""
def oauth(): if not request.args["code"]: return jsonify({"Error": "sadcat"}), 500 resp = requests.post( "https://slack.com/api/oauth.v2.access", { "code": request.args["code"], "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, }, ) if resp.status_code == 200: data = resp.json() bot_token = data["access_token"] workspace_data = requests.post( "https://slack.com/api/auth.test", headers={"Authorization": "Bearer {}".format(bot_token)}, ).json() workspace_url = workspace_data["url"] workspace = re.match( r"https://([a-zA-Z\-0-9]+)\.slack\.com", workspace_url ).group(1) store_bot_token(get_course(workspace), data["team"]["id"], bot_token) store_user_token( data["authed_user"]["id"], data["authed_user"]["access_token"] ) with connect_db() as db: db("DELETE FROM silenced_users WHERE user = (%s)", [data["authed_user"]["id"]]) return redirect(workspace_url) return jsonify({"Error": "sadcat"}), 500
class ArticleModel(object): db = connect_db() collection = db["articles"] def __init__(self, url): self.url = url self.tokens = [] self.text = "" self.entities = [] self.tree = {} @classmethod def all(cls): return list(cls.collection.find()) @classmethod def find_by_id(cls, id): articles = list(cls.collection.find({"_id": ObjectId(id)})) return articles[0] @classmethod def find_by_url(cls, url): return list(cls.collection.find({"url", url}))[0] def save(self): return self.collection.insert({"url", self.url}) def upsert(self, fields): return self.collection.update_one({"url": fields["url"]}, {"$set": fields}, True)
async def list_loggers(displayed_only: bool = False): async with connect_db() as connection: query = sa.select([Logger]) if displayed_only: query = query.where(Logger.is_displayed) result = await connection.execute(query) return [dict(row) for row in await result.fetchall()]
def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db
def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = db.connect_db() return g.sqlite_db
def revoke_key(course): name = request.args["client_name"] with connect_db() as db: db( "DELETE FROM auth_keys WHERE client_name = (%s) and course = (%s)", [name, course], ) return redirect("/")
def load_stored_file(file_name): with connect_db() as db: out = db( "SELECT * FROM stored_files WHERE file_name=%s;", [file_name] ).fetchone() if out: return out[1] abort(404)
def index(): out = [app.general_info.render()] with connect_db() as db: for course, endpoint in db( "SELECT course, endpoint FROM courses").fetchall(): if is_staff(app.remote, course): out.append(app.help_info.render(course)) return "".join(out)
def check_auth(app): email = get_user_data(app)["email"] with connect_db() as db: authorized = [ prefix + "@berkeley.edu" for (prefix, *_) in db("SELECT * FROM authorized").fetchall() ] return email in authorized
def remove_admin(course): email = request.args["email"] with connect_db() as db: db( "DELETE FROM course_admins WHERE email=(%s) AND course=(%s)", [email, course], ) return redirect(url_for("index"))
def remove_domain(course): domain = request.args["domain"] with connect_db() as db: db( "DELETE FROM domains_config WHERE domain = (%s) AND course = (%s)", [domain, course], ) return redirect("/")
def setup(self): if len(sys.argv) > 1: dbfile = sys.argv[1] con = db.connect_db(dbfile) else: con = db.connect_db() self.con = con self.setup_widgets() # Select first table by default all_tbls = all_tables(con) if len(all_tbls) > 0: self.select_table(all_tbls[0]) # Query all records self.run_query(self.state.tbl, "", "")
def set_endpoint(course): endpoint = request.form["endpoint"] with connect_db() as db: db( "UPDATE courses SET endpoint = (%s) WHERE course = (%s)", [endpoint, course], ) return redirect("/")
def init_db(): with connect_db() as db: db( """CREATE TABLE IF NOT EXISTS domains_config ( domain varchar(128), course varchar(128) )""" )
def test_get_comments(self): with db.connect_db() as conn: db_add(conn, tdc.TEST_ROWS['owners']) db_add(conn, tdc.TEST_ROWS['projects']) db_add(conn, tdc.TEST_ROWS['comments']) result = db.get_comments(conn, tdc.MOCK_PROJ_UUID_11) self.assertEqual(result[1][4], "Owner 1, project 1, comment 2")
def workspace_name(course): with connect_db() as db: workspace = db( "SELECT workspace FROM slack_config WHERE course=(%s)", [course]).fetchone() if workspace: return jsonify(workspace[0]) else: return jsonify(None)
def get_group_order(): """Return group order in dataframe.""" cnx, cursor = connect_db() query = """select name, `order` from types where `group`=1""" cursor.execute(query) result = cursor.fetchall() result = pd.DataFrame(result, columns=["group", "order"]) cnx.close() return result
def get_palette(): """Return the hexadecimal color code in a dictionary.""" cnx, cursor = connect_db() query = """select name, color from types""" cursor.execute(query) color = cursor.fetchall() cnx.close() color = {x[0]: '#' + format(x[1], 'x') for x in color} return color
def get_group_order(): """Return group order in dataframe.""" cnx, cursor = connect_db() query = """select name, `order` from types where `group`=1""" cursor.execute(query) result = cursor.fetchall() result = pd.DataFrame(result, columns=['group', 'order']) cnx.close() return result
def __init__(self, db_name=DB_NAME_MARKETPLACE): if not os.path.isfile(db_name): init_db(db_name) self.db = db.connect_db(db_name) if self.db is not None: log_info("DB {} succesfully loaded".format(db_name)) else: log_error("Error opening marketplace DB")
def get_db(): start = timer() db = getattr(g, 'firebird_db', None) if db is None: db = g.firebird_db = connect_db(app.config['DB_CONNECTION_STRING'], app.config['DB_USERNAME'], app.config['DB_PASSWORD']) print('DB CONN {:.4f}ms'.format((timer() - start) * 1000)) return db
def test_get_project(self): with db.connect_db() as conn: db_add(conn, tdc.TEST_ROWS['owners']) db_add(conn, tdc.TEST_ROWS['projects']) result = db.get_project(conn, tdc.USER_UUID_1, tdc.MOCK_PROJ_UUID_12) self.assertEqual(result['project_id'], tdc.MOCK_PROJ_UUID_12) self.assertEqual(result['project_name'], tdc.PROJECT_12)
def set_db(): (conn, cursor) = connect_db() cursor.execute("""CREATE TABLE IF NOT EXISTS worklogs ( id integer PRIMARY KEY, description text NOT NULL, time float NOT NULL, issue text NOT NULL, day date NOT NULL );""")
def get_endpoint_id(course): with connect_db() as db: endpoint = db( "SELECT endpoint_id FROM courses WHERE course = (%s)", [course]).fetchone() if endpoint: return jsonify(endpoint[0]) else: return jsonify(None)
def get_endpoint(course): # note: deliberately not secured, not sensitive data with connect_db() as db: endpoint = db("SELECT endpoint FROM courses WHERE course = (%s)", [course]).fetchone() if endpoint: return jsonify(endpoint[0]) else: return jsonify(None)
def __init__(self, db_name=DB_NAME_TIGRIS): if not os.path.isfile(db_name): init_db(db_name) self.db = db.connect_db(db_name) if self.db is not None: log_info("DB {} succesfully loaded".format(db_name)) else: log_error("Error opening tigris DB")
def setup_shortlink_generator(): with connect_db() as db: db("""CREATE TABLE IF NOT EXISTS studentLinks ( link varchar(128), fileName varchar(128), fileContent BLOB)""") db("""CREATE TABLE IF NOT EXISTS staffLinks ( link varchar(128), fileName varchar(128), fileContent BLOB)""")
def init_db(): with connect_db() as db: db( """CREATE TABLE IF NOT EXISTS course_admins ( email varchar(128), name varchar(128), course varchar(128), creator varchar(128) )""" )
def get_all_types(): """Return all types name and order in dataframe.""" cnx, cursor = connect_db() query = """select a.name, b.`order` from types a, types b where a.parent=b.guid""" cursor.execute(query) result = cursor.fetchall() result = pd.DataFrame(result, columns=["type", "order"]) cnx.close() return result
def get_user_token(user): with connect_db() as db: out = db("SELECT token FROM tokens WHERE user=%s", (user, )).fetchone() if not out: check = db("SELECT user FROM silenced_users WHERE user=%s", (user, )).fetchone() if check: # user doesn't want to use the tool :( return REJECTED return UNABLE return out["token"]
def list_uid(): conn = db.connect_db() cursor = conn.cursor() cursor.execute('select * from mgt;') uid_list = [] for x in cursor.fetchall(): uid_list.append(x[0]) return uid_list cursor.close() conn.close()
def get_all_types(): """Return all types name and order in dataframe.""" cnx, cursor = connect_db() query = """select a.name, b.`order` from types a, types b where a.parent=b.guid""" cursor.execute(query) result = cursor.fetchall() result = pd.DataFrame(result, columns=['type', 'order']) cnx.close() return result
def get_data(start, end): cnx, cursor = connect_db() query = """select intervals.from, intervals.to, delta, a.name, b.name, comment from types a, types b, intervals where intervals.type = a.guid and a.parent = b.guid and intervals.to > {0} and intervals.from < {1} order by intervals.to""".format( start, end ) cursor.execute(query) entries = cursor.fetchall() cnx.close() return entries
def get_type_order(group): """Return group order in dataframe. :param group: str, group name """ cnx, cursor = connect_db() query = """select a.name, a.`order` from types a, types b where a.parent=b.guid and b.name='{0}'""".format( group ) cursor.execute(query) result = cursor.fetchall() result = pd.DataFrame(result, columns=["type", "order"]) cnx.close() return result
def update_feeds(feed_callbacks): ''' accepts list of updated feeds, flushes existing feed data based on 'src' column adds (refreshed) feed data to db ''' dba = db.connect_db() db.execute(dba, 'delete from hosts') for feed_name, callback in feed_callbacks.iteritems() : print 'fetching %s feed data' % feed_name result = callback() print 'parsing %d hosts' % len(result) if len(result) > 0 : db.flush_hosts(dba, feed_name) add_feed_data(dba, result) print '%d hosts in database' % db.get_db_size(dba)[0]
def get_sleep_data(start, end): """ Get sleep entries from data base from 'start' to 'end'. :param start: (int) unix timestamp for start point. :param end: (int) unix timestamp for end point. :return: a list of tuples (start, end, duration). """ cnx, cursor = connect_db() query = """select intervals.from, intervals.to, delta from types, intervals where intervals.type = types.guid and types.name = 'Sleep' and intervals.to > {0} and intervals.to < {1} order by intervals.to""".format( start, end ) cursor.execute(query) sleep_entries = cursor.fetchall() cnx.close() return sleep_entries
def main(): # try: # connect = db.connect_db() # db.init_db(connect) # print 'Connected to database' # except: # print "Database not ready to be used" try: connect = db.connect_db() db.init_db(connect) print 'Connected to database' except: print "Database not ready to be used" # username = '******' # scope = 'playlist-read-private playlist-read-collaborative' # token = util.prompt_for_user_token(username,scope) # connect.close() # return render_template('index.html', name='hello') url_args = "&".join(["{}={}".format(key,urllib.quote(val)) for key,val in auth_query_parameters.iteritems()]) auth_url = "{}/?{}".format(SPOTIFY_AUTH_URL, url_args) print auth_url return redirect(auth_url)
elif data == "/pomoc": data = "/pomoc -> prikazuje ovaj tekst\n\r/izlaz -> prekida vezu s serverom\n\r/reci [poruka] -> Saljes poruku ostalim igracima\n\r/ponovi [poruka] -> ponovi poslanu poruku\n\r" veza.send(enkodiraj(data)) else: veza.send(enkodiraj("Ovo što ste napisali nema smisla...\n\r")) TCP_IP = "127.0.0.1" #TCP_IP = "192.168.100.239" TCP_PORT = 8880 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(50) #otvaranje veze svijet = db.connect_db() for j in range(len(svijet)): for l in range(len(svijet[j])): svijet[j][l] = svijet[j][l].encode('utf-8') print("Server je startan.") while 1: conn, addr = s.accept() #prihvacanje veze print("Klijent spojen: ", addr) #prikazuje tko se spojio lock.acquire() lista_veza.append(conn) #dodaju se inf o vezi lista_adresa.append(addr[1]) lock.release() kom_veza = Thread(target=komunikacija, args=(conn,addr,))#definiranje dretve kom_veza.setDaemon(True)
def get_db(): if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db(app.config['DATABASE']) return g.sqlite_db
continue wangqianhetong = order_info[0] kehuxingming = order_info[1] kehushengfenzheng = order_info[2] guohuzhuanyuan = order_info[3] yuyueshijian = order_info[4] dateType = order_info[5] svpdUpLoadType = '-1' spvdName = '东城预约缴税' svpdUpLoadTypeDetail = '-1' spvdCode = 'ZN0870' svpdDetailCategory = '101336' checkBoxProduct = '2925_2188_2566' #eoContent = '网签合同号:' + wangqianhetong + ',客户姓名:' + kehuxingming + ',身份证号:' + kehushengfenzheng + ',过户专员:' + guohuzhuanyuan + ',预约时间:' + yuyueshijian + ',' + dateType eoContent = '网签合同号:' + wangqianhetong + ',客户姓名:' + kehuxingming + ',客户身份证号:' + kehushengfenzheng + ',过户专员:' + guohuzhuanyuan + ',预约时间:' + yuyueshijian + ',' + dateType post_info = {'tsname' : tsname, 'tsuserid' : tsuserid, 'marketemail' : marketemail, 'tsphone' : tsphone, 'wangqianhetong' : wangqianhetong, 'kehuxingming' : kehuxingming, 'kehushengfenzheng' : kehushengfenzheng, 'guohuzhuanyuan' : guohuzhuanyuan, 'yuyueshijian' : yuyueshijian, 'dateType' : dateType, 'svpdUpLoadType' : svpdUpLoadType, 'spvdName' : spvdName, 'svpdUpLoadTypeDetail' : svpdUpLoadTypeDetail, 'spvdCode' : spvdCode, 'svpdDetailCategory': svpdDetailCategory, 'checkBoxProduct' : checkBoxProduct, 'eoContent' : eoContent, 'post_account' : account} #dongchengjiaoshui_sync(jsessionid, post_info, order_info) #dongchengjiaoshui_async(jsessionid, post_info, order_info) tasks.append(gevent.spawn(dongchengjiaoshui_submitorder, jsessionid, post_info, order_info)) gevent.joinall(tasks) if __name__ == '__main__': db.connect_db() while True: dongchengjiaoshui()
def set_config(app): db = connect_db(app.config['DATABASE']) set_cookie_config(app, db) set_mail_config(app, db) db.close()
def before_request(): g.db = connect_db() g.cursor = g.db.cursor() if app.config['SECURE']: csrf_protect()
names = [ 'MyPinnings Recommendations', 'Bicycle & Motor Bikes', 'Cars', 'Collectibles (Arts & Crafts)', 'Beauty', 'Books', 'Cell Phones', 'Fashion', 'Gadgets', 'Jewelry', 'Money', 'Movies & Music', 'Shoes', 'Travel & Experiences', 'Watches', 'Wine & Champagne', ] import db db = db.connect_db() names = [{'name': x} for x in names] db.multiple_insert('categories', names)
def __init__(self): self.seriesdb = connect_db() self.store = st.Store(self.seriesdb) socket.setdefaulttimeout(60)
def test_connect(self): c = db.connect_db() cur = c.cursor() # ensure the post table is there cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('post',)) self.assertEqual(cur.fetchone()[0],True)
def before_request(): g.db = db.connect_db()
def load_user(id): g.db = db.connect_db() # Since this isn't a request we need to connect first. user = db.query_db('select * from users where id = ?', [id], one=True) g.db.close() return User(user['id'], user['username'], user['password'], user['name'], user['city'])
return () id=name=year=rate=address = None error_happened = False try: id = int((re.findall(_DOUBAN_MOVIE_ID_PATTERN, response))[0]) name = (re.findall(_DOUBAN_MOVIE_NAME_PATTERN, response))[0] year = (re.findall(_DOUBAN_MOVIE_YEAR_PATTERN, response))[0] rate = float((re.findall(_DOUBAN_MOVIE_RATE_PATTERN, response))[0]) address = seed except BaseException, e: error_happened = True if not error_happened: movie = Movie(id=id, name=name, year=year, rate=rate, address=address) if find_movie(movie) is None: print(movie.__repr__()) save_movie(movie) return set(re.findall(_DOUBAN_MOVIES_PATTERN, response)) def start(): crawl(_DOUBAN_MOVIE_SEED) if __name__ == '__main__' : connect_db() print _HELP_STRING
def test_connect(self): c = db.connect_db() cur = c.cursor() # ensure the post table is there cur.execute("select exists(SELECT name FROM sqlite_master WHERE type='table' AND name=?);", ('post',)) self.assertEqual(cur.fetchone()[0],True)
#!/usr/bin/python import web from web import form import random import string import hashlib ## from db import connect_db import ser PASSWORD = '******' db = connect_db() sess = ser.sess def tpl(*params): global template_obj return template_obj(*params) def template_closure(directory): global settings templates = web.template.render(directory, globals={'sess': sess, 'tpl': tpl}) def render(name, *params): return getattr(templates, name)(*params) return render