def create_app(): # app = Flask(__name__) from config import init_config init_config(app) # from sentry import init_sentry # init_sentry(app) from model import init_db init_db(app) from controller import init_blueprint init_blueprint(app) # # if False and app.config.get('CRON_STATE') is True: # from cron import init_cron # init_cron(app) from utils import init_util init_util(app) # from utils.kafka import KafkaClient # KafkaClient.init_kafka() # # from redisdb import init_redis # init_redis(app) return app
def run_spider(): """ 运行爬虫 :return: """ # drop_db() init_db() logging.info("Spider start ... city: {0}, districts: {1}".format(CITY, ','.join(DISTRICTS))) spider = LianJiaSpider( city=CITY, districts=DISTRICTS, ) # 爬取所有小区信息(首次必须) spider.crawl_district_pool(module='community_info') # 爬取在售房源: 3种方式 # 1. 按照地区爬取 # spider.crawl_district_pool(module='sale_info') # 2. 按照商圈爬取(推荐) biz_circles = spider.query_biz_circle(districts=DISTRICTS_CN) spider.set_request_params(max_workers=3, delay=0.5) # 限速 spider.crawl_search_pool(module='sale_info', collection=biz_circles, coll_start=1) # 3. 按照社区爬取 # communities = spider.query_community(biz_circle=biz_circles) # spider.crawl_search_pool(module='sale_info', collection=communities) # 爬取历史成交 spider.set_request_params(max_workers=1, delay=3) # 限速 spider.crawl_search_pool(module='transaction_info', collection=biz_circles, coll_start=1) # spider.crawl_search_pool(module='transaction_info', collection=communities) logging.info("Spider finished ...")
def make_app(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) environment = os.environ.get("APPLICATION_ENV", "development") application = Flask(__name__) application.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'DATABASE_URL') application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False application.app_context().push() # Configura as API's api.init_app(application) # inicia banco de dados init_db(application) # Configuração do Sentry sentry_sdk.init(dsn=os.environ.get("SENTRY_DSN"), integrations=[FlaskIntegration()], environment=environment) # Producer do Kafka logging.info("Conectando no Kafka: " + os.environ.get("KAFKA_BROKERS") + " / " + os.environ.get("KAFKA_SECURITY_PROTOCOL")) connect_producer( os.environ.get("KAFKA_BROKERS"), security_protocol=os.environ.get("KAFKA_SECURITY_PROTOCOL")) return application
def master_main(cfg): set_logging('master.log') basepath = os.path.dirname(sys.path[0]) schemapath = os.path.join(basepath, 'conf', 'schema.sql') dbcfg = cfg['master']['database'] model.init_db(dbcfg, schemapath) global _MASTER m = Master(cfg) m.start()
def client(): app.config["TESTING"] = True os.environ["test"] = "True" model.initialize(app) model.init_db() client = app.test_client() yield client model.clear_db()
def ui_main(config, debug=False): set_logging('ui.log') logging.info('starting manger ui...') dbcfg = config['master']['database'] init_db(dbcfg) global _CONFIG _CONFIG = config _APP.jinja_env.variable_start_string = '{-' _APP.jinja_env.variable_end_string = '-}' _APP.jinja_env.auto_reload = True _APP.config['TEMPLATES_AUTO_RELOAD'] = True servercfg = config['ui']['server'] _APP.run(host=servercfg['host'], port=servercfg['port'], debug=debug)
def handler(): db = init_db() sess = get_session() campaigns = db.query(campaign.id,campaign.desc).filter(campaign.profiles.any(id=sess['uid'])).all() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(pstatuses=status_profile, campaigns=campaigns,type=profile_types.index(request.params.get('type') if 'type' in request.params else 'contact'),profile=curr_prof)
def handler(cid): db = init_db() sess = get_session() contact = db.query(profile).filter(profile.id==cid).first() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(profile_id=cid, feedback_type=FEEDBACK_TYPE,status_type=status,profile=curr_prof,contact=contact)
def handler(cid): db = init_db() item = db.query(profile).filter(profile.id == cid).first() sess = get_session() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(profile_id=cid, chat_type=chat_type,contact=item,profile=curr_prof)
def setUp(self): dbconfig = { 'info': { 'type': 'sqlite', 'host': 'saa018', 'name': 'node-monitor', 'user': '******', 'password': '******' }, 'tsd': { 'type': 'opentsdb', 'host': 'localhost', 'port': 4242 } } model.init_db(dbconfig, '../conf/schema.sql')
def handler(): url = TWITTER_ACCESS_TOKEN_URL+'?oauth_token=%s&oauth_verifier=%s' % (request.GET.get('oauth_token'),request.GET.get('oauth_verifier')) resp, content = TWITTER_client.request(url) if resp['status'] == '200': print 'OAuthGetAccessToken OK' db = init_db() try: sess = get_session() curr_uid = sess['uid'] except : db.close() bottle.redirect(url_root) curr_profile = db.query(profile).filter(profile.id==curr_uid).first() if curr_profile: curr_profile.t_oauth_token = urlparse.parse_qs(content)['oauth_token'][0] curr_profile.t_oauth_token_secret = urlparse.parse_qs(content)['oauth_token_secret'][0] curr_profile.problem="" curr_profile.save(session=db) db.close() bottle.redirect(url_root) else: db.close() print 'OAuthGetAccessToken status: %s' % resp['status'] print content bottle.redirect(url_root)
def test_email_tree(self): input = open("data.pkl","rb") mail = pickle.load(input) for y in mail: print "=======######## GOt email "+(y['subject'] if 'subject' in y else "NO SUBJECT") +" mid "+(y['id'] if 'id' in y else "NO ID") + " parent id "+(y['parent'] if ('parent' in y and y['parent'] is not None) else "NO PARENT") db = init_db() contact = db.query(profile).filter(profile.pemail == "*****@*****.**").first() currchat = makechatfromemail(y) if not contact.chats: currchat.save(session=db) contact.chats.append(currchat) contact.save(session=db) print "save single email" continue contact.chats.sort(key=lambda x:x.ts) for old in contact.chats: obj = json.loads(old.details) if obj['id'] == y['id']: continue if old.type == CHAT_EMAIL: print "OLD email "+(obj['subject'] if 'subject' in obj else "NO SUBJECT") +" mid "+(obj['id'] if 'id' in obj else "NO ID" )+ " parent id "+(obj['parent'] if ('parent' in obj and obj['parent'] is not None) else "NO PARENT") if obj['id'] == (y['parent'] if 'parent' in y else ""): print "EMAIL " + y['id'] + " is reply to " + old['id'] old.replies.append(currchat) old.save(session=db) currchat.save(session=db) contact.chats.append(currchat) contact.save(session=db) continue currchat.save(session=db) contact.chats.append(currchat) contact.save(session=db) return True
def handler(cid): db = init_db() sess = get_session() g_oauth_token,g_oauth_token_secret,email = db.query(profile.g_oauth_token,profile.g_oauth_token_secret,profile.pemail).filter(profile.id==sess['uid']).first() if g_oauth_token is None: db.close() bottle.redirect(url_root+'/g/start_oauth') contact = db.query(profile).filter(profile.id==cid).first() last_email = db.query(chat).filter(and_(chat.profile_id==cid,chat.type==CHAT_EMAIL)).order_by(chat.ts).first() if not contact: db.close() bottle.redirect(url_root_contacts) if last_email: since = (datetime.datetime.fromtimestamp(last_email.ts)).strftime("%Y/%m/%d") else: since = "1970/01/01" token = oauth.Token(g_oauth_token,g_oauth_token_secret) conn = imaplib.IMAP4_SSL('imap.googlemail.com') conn.debug = 4 try: conn.authenticate((GOOGLE_RESOURCE_URL % email), GOOGLE_consumer, token) except Exception as e: print e db.close() bottle.redirect(url_root+'/g/start_oauth') conn.select("INBOX",readonly=True) print "geting email for "+contact.pemail threading.Thread(target=emails,args=(conn,contact.pemail,since)).start() sess = get_session() sess['msg'] = "Emails for %s will be fetched in a few milliseconds" % contact.pemail sess['msg-old'] = False db.close() bottle.redirect(url_root_contacts+'/%s/emails' % cid)
def handler(cid): db = init_db() item = db.query(profile).filter(profile.id == cid).first() sess = get_session() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(items=item,cid=cid,profile=curr_prof)
def test_data(self): db = init_db() chats = db.query(chat) for c in chats: obj = json.loads(c.details) if 'body' in obj: if 'And about the gain and expenses' in obj['body']: print c.id return True
def __init__(self): threading.Thread.__init__(self) if not os.path.exists('/tmp/converterdir'): os.makedirs('/tmp/converterdir') #flog = open('/tmp/converterdir/test.log', 'w') self.flog = open('/var/opt/converter/convertThread.log', 'w') #Вырубили все инстанцы ОО и запустили новый subprocess.call("killall -u 'root' -q soffice ", shell=True, stdout=self.flog) subprocess.Popen( '/usr/bin/ooffice -accept="socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -norestore -nofirststartwizard -nologo -headless ', shell=True, stdout=self.flog) #Дождались пока он точно стартанёт time.sleep(5) model.init_db()
def handler(cid): db = init_db() obj = db.query(profile).filter(and_(profile.id == cid, profile.uuid == request.POST.get('uuid'))).first() if obj is None: db.close() bottle.redirect(url_root_contacts) obj.update(request.POST,session=db) db.close() bottle.redirect(url_root_contacts + '/' + cid)
def handler(cid,id): db = init_db() obj = db.query(chat).filter(chat.id==id).first() item = db.query(profile).filter(profile.id == cid).first() sess = get_session() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(chat=obj,contact=item,profile=curr_prof)
def test_campaigns(self): db = init_db() new_campaign = campaign(desc="Test Campaign") db.add(new_campaign) db.commit() request = db.query(campaign).filter_by(desc="Test Campaign").first() print request.desc self.assertTrue(request.desc is new_campaign.desc)
def handler(id): db = init_db() sess = get_session() obj = db.query(campaign).filter(and_(campaign.profiles.any(id=sess['uid']),campaign.id==id,campaign.uuid == request.POST.get('uuid'))).first() if obj is None: db.close() bottle.redirect(url_root) obj.update(request.POST,session=db) db.close() bottle.redirect(url_root + '/' + id)
def handler(): sess = get_session() db = init_db() objs = db.query(campaign).filter(campaign.profiles.any(id=sess['uid'])).all() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() collect = [] for x in objs: collect.extend(x.profiles) db.close() return dict(items=collect,profile=curr_prof)
def handler(): db = init_db() sess = get_session() objs = db.query(campaign).filter(campaign.profiles.any(id=sess['uid'])).all() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() isoauth = True if (curr_prof.g_oauth_token is not None and curr_prof.g_oauth_token_secret is not None) else False istoauth = True if (curr_prof.t_oauth_token is not None and curr_prof.t_oauth_token_secret is not None) else False istoauth = False if curr_prof.problem != "" else istoauth db.close() return dict(items=objs,isoauth=isoauth,istoauth=istoauth,profile=curr_prof,sess=sess)
def handler(): sess = get_session() db = init_db() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() all_campaigns = db.query(campaign).filter(campaign.profiles.any(id=sess['uid'])).all() profiles = [] for obj in all_campaigns: profiles.extend(obj.profiles) db.close() return dict(contacts=profiles,profile=curr_prof,feedback_type=FEEDBACK_TYPE,status_type=status)
def handle(cid): db = init_db() obj = chat() prof = db.query(profile).filter(profile.id == cid).first() obj.update(request.POST,session=db) if prof: prof.chats.append(obj) prof.save(session=db) db.close() bottle.redirect(url_root_contacts + '/' + cid + '/chats/' + str(obj.id)) if obj else bottle.redirect( url_root_contacts)
def handle(cid): db = init_db() obj = feedback() prof = db.query(profile).filter(profile.id == cid).first() obj.update(request.POST,session=db) if prof: prof.feedbacks.append(obj) prof.save(session=db) db.close() bottle.redirect(url_root+ '/feedbacks') if obj else bottle.redirect( url_root_contacts)
def handler(cid): db = init_db() sess = get_session() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() contact_profile = db.query(profile).filter(profile.id==cid).first() print "Mentioned "+str(curr_prof.twitter)+" mentioner "+str(contact_profile.twitter) tweets = db.query(tweet).filter(and_(tweet.mentioned==curr_prof.twitter,tweet.mentioner==contact_profile.twitter)).order_by(desc(tweet.ts)) db.close() return dict(items=tweets,profile=curr_prof,contact=contact_profile)
def __init__(self, root_url): self.root_url = root_url self.domain = get_tld(root_url) self.links_await = set() # 带爬取的url self.links_visited = set() # 已爬取的url self.attachment_saved = set() # 已保存的附件url self.links_all_dict = {} # 以字典形式保存所有的链接{url: title},不含附件 self.s = requests.Session() retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[404, 500, 502, 503, 504]) self.s.mount('http://', HTTPAdapter(max_retries=retries)) # 初始化数据库和附件保存目录 init_db() self.target_dir = os.path.join(TARGET_DIR, self.domain) if not os.path.exists(self.target_dir): os.mkdir(self.target_dir)
def handler(cid): db = init_db() obj = db.query(profile).filter(profile.id == cid).first() sess = get_session() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() isoauth = True if (curr_prof.g_oauth_token is not None and curr_prof.g_oauth_token_secret is not None) else False istoauth = True if (curr_prof.t_oauth_token is not None and curr_prof.t_oauth_token_secret is not None) else False istoauth = False if curr_prof.problem != "" else istoauth db.close() return dict(obj=obj,campaign=obj.campaign,pstatuses=status_profile,profile=curr_prof,isoauth=isoauth,istoauth=istoauth) if obj else bottle.redirect( url_root_contacts)
def login(user, passwd): db = init_db() user = db.query(profile).filter(and_(profile.name==user,profile.passwd==passwd)).first() if user: sess = get_session() sess['uid'] = user.id sess['loggedin'] = True db.close() else: db.close() return
def handler(): sess = get_session() db = init_db() objs = db.query(campaign).filter(campaign.profiles.any(id=sess['uid'])).all() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() profs = [] for camp in objs: for prof in camp.profiles: profs.append(prof) db.close() return dict(items=profs,profile=curr_prof)
def handler(id): sess = get_session() db = init_db() obj = db.query(campaign).filter(and_(campaign.profiles.any(id=sess['uid']),campaign.id==id)).first() if(obj is None): db.close() bottle.redirect(url_root) types = campaign_type_get_all(exclude=obj.campaign_type) curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(item=obj, ctypes=types, uattrs=json.loads(obj.attrs), gains=gaintypes, expenses=expensetypes, status=status, ugains=json.loads(obj.gains), uexpenses=json.loads(obj.expenses),profile=curr_prof)
def handler(): sess = get_session() db = init_db() obj = profile() obj.update(request.POST,session=db) if obj and 'campaign_id' in request.POST: camp = db.query(campaign).filter(and_(campaign.profiles.any(id=sess['uid']),campaign.id == request.POST.get('campaign_id'))).first() if camp: obj.campaign.append(camp) obj.save(session=db) db.close() bottle.redirect(url_root_contacts)
def welcome_service(): print("config.DATA_PERSISTENCE_FLAG=" + str(config.DATA_PERSISTENCE_FLAG)) print("config.DATABASE_LOCATION" + str(config.DATABASE_LOCATION)) print("-- database setup start --") ret = model.init_db() if ret is True: print("-- database setup success --") else: print("-- database setup failed --") response.headers['Access-Control-Allow-Origin'] = '*' return template("top.html", test="to the start page...")
def handler(cid,id): sess = get_session() db = init_db() current_profile = db.query(profile).filter(profile.id==sess['uid']).first() curr_chat = db.query(chat).filter(chat.id==id).first() reply = chat() reply.update(request.POST,session=db) curr_chat.replies.append(reply) curr_chat.save(session=db) reply.save(session=db) current_profile.chats.append(reply) current_profile.save(session=db) db.close() bottle.redirect(url_root_contacts+'/%s/chats/%s/reply' % (cid,id))
def main(): init_db() users = User.all() for u in users: log('user stat <{}> <{}> <{}>'.format(len(u.repositories), u.name, u.url)) for r in Repository.invalid: log('invalid repository', r) for c in Contribution.wrong: log('wrong contribution', c) us = sorted(users, key=lambda u: u.star, reverse=True) for i, u in enumerate(us): # if len(u.contribution) > 0 and u.login not in u.contribution[0].repository.name_with_owner: formatted = 'user star:' formatted += '{i:3} {u.login:15} {int(u.star):5} ' for c in u.contribution[:3]: r = c.repository formatted += '{r.name_with_owner:40} {r.language:12} {int(c.count):5} ' log(formatted)
def handler(cid): db = init_db() obj =db.query(profile).filter(profile.id==cid).first() gtid = defaultdict(list) for x in obj.chats: js = json.loads(x.details) if 'gtid' in js: gtid[js['gtid']].append(x) item = db.query(profile).filter(profile.id == cid).first() sess = get_session() curr_prof = db.query(profile).filter(profile.id==sess['uid']).first() db.close() return dict(chats=gtid,contact=item,profile=curr_prof,sess=sess)
def handler(): db = init_db() obj = campaign() obj.update(request.POST,db) sess = get_session() current_profile = db.query(profile).filter(profile.id==sess['uid']).first() if current_profile: obj.profiles.append(current_profile) obj.save(session=db) current_profile.campaign.append(obj) current_profile.save(session=db) if obj is None: db.close() return "error" db.close() bottle.redirect(url_root)
def handler(id): sess = get_session() db = init_db() obj = db.query(campaign).filter(and_(campaign.profiles.any(id=sess['uid']),campaign.id==id)).first() if obj is None: bottle.redirect(url_root) todelete =[] for p in obj.profiles: print "\n\nremoving "+p.name +" from campaign "+obj.desc todelete.append(p) del obj.profiles db.commit() db.delete(obj) db.commit() for t in todelete: if t.profile_type != PROFILE_OWNER: db.delete(t) db.commit() db.close() bottle.redirect(url_root)
def handler(cid, id): db = init_db() obj = db.query(chat).filter(chat.id == id).first() obj.update(request.POST,session=db) db.close() return bottle.redirect(url_root_contacts + '/%s/chats/%s' % (cid, id))
#!/usr/bin/env python # coding:utf-8 import logging import traceback from flask import Flask, request from model import init_db from msg_proc import QQMessage app = Flask(__name__) db = init_db(app) with app.app_context(): db.create_all() @app.route("/bot", methods=['POST']) def qqbot(): try: qq_msg = QQMessage(request.data) qq_msg.proc_message() except Exception as e: print 'Error occor: %s' % e print traceback.format_exc() finally: return '' if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) app.run(host='127.0.0.1', port=60002, debug=True, threaded=True)
def test_campaign_types(self): db = init_db() for obj in db.query(campaign_type).order_by(campaign_type.id): print obj.desc self.assertTrue(obj.desc in ctypes)
def main(): env = os.environ.get('ENV') webhook_url = os.environ.get('WEBHOOK_URL') port = os.environ.get('PORT_T') mode = os.environ.get('MODE') if env == "GCLOUD": project_id = os.environ.get('GCLOUD_PROJECT_ID') logging.info(os.environ.get('GCLOUD_PROJECT_ID')) gcl = gcloud.Gcloud(project_id) token = gcl.access_secret_version() else: token = os.environ.get("TOKEN") #Create Updater updater = Updater(token=token, use_context=True) conv_handler = ConversationHandler( entry_points=[ CommandHandler('start', start), CommandHandler('add_activity', add_activity_command_handler), CommandHandler('execute_activity', execute_activity_command_handler), CommandHandler('show_score', show_score_command_handler), CommandHandler('show_activities', show_activities_command_handler), CommandHandler('show_log', show_log_command_handler), CommandHandler('delete_activity', delete_command_handler), CommandHandler('cancel_activity', cancel_activity_command_handler), CommandHandler('update_activity', update_activity_command_handler) ], states={ ACTIVITY: [MessageHandler(Filters.all, add_activity, pass_user_data=True)], POINTS: [MessageHandler(Filters.all, add_points, pass_user_data=True)], IDLE: [CallbackQueryHandler(idle, pass_user_data=True)], DELETE: [CallbackQueryHandler(delete, pass_user_data=True)], EXECUTE_ACTIVITY: [CallbackQueryHandler(execute_activity, pass_user_data=True)], CANCEL: [CallbackQueryHandler(cancel_activity, pass_user_data=True)], UPDATE: [CallbackQueryHandler(what_to_update, pass_user_data=True)], UPDATE_FINILAZE: [CallbackQueryHandler(update_activity, pass_user_data=True)], CHANGE_ACTIVITY_NAME: [ MessageHandler(Filters.all, change_activity_name, pass_user_data=True) ], CHANGE_ACTIVITY_POINTS: [ MessageHandler(Filters.all, change_activity_points, pass_user_data=True) ] }, fallbacks=[ CommandHandler('start', start), CommandHandler('execute_activity', execute_activity_command_handler), CommandHandler('add_activity', add_activity_command_handler), CommandHandler('show_score', show_score_command_handler), CommandHandler('show_activities', show_activities_command_handler), CommandHandler('show_log', show_log_command_handler), CommandHandler('cancel', cancel), CommandHandler('delete_activity', delete_command_handler), CommandHandler('cancel_activity', cancel_activity_command_handler), CommandHandler('update_activity', update_activity_command_handler) ]) #Create Dispatcher disp = updater.dispatcher #Add handlers to updater disp.add_handler(conv_handler) #Init database init_db() if mode == 'webhook': #Start polling from Telegram updater.start_webhook(listen='0.0.0.0', port=port, url_path=token) else: updater.start_polling() updater.idle()
def init(): model.init_db() flash("Initialisation DONE!", 'error') return redirect(url_for('login'))
CORS(application, resources={r'/*': {'origins': '*'}}) database_uri = 'mysql+pymysql://{dbuser}:{dbpass}@{dbhost}/{dbname}'.format( dbuser=os.environ['DBUSER'], dbpass=os.environ['DBPASS'], dbhost=os.environ['DBHOST'], dbname=os.environ['DBNAME']) application.config.update( SQLALCHEMY_DATABASE_URI=database_uri, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) db.init_app(application) with application.app_context(): init_db() @application.route('/projects', methods=['GET', 'POST']) def get_projects(): if request.method == 'POST': try: title = str(request.json.get('title')) info = str(request.json.get('info')) image_url = str(request.json.get('url')) project_request = ProjectsInfo(id=None, title=title, info=info, image_url=image_url) db.session.add(project_request)
from flask import Flask, request, render_template, url_for import model app = Flask(__name__) model.init_db() byte_skills = [ 'python', 'javascript', 'machine-learning', 'deep-learning', 'nlp', 'web-technologies', 'front-end', 'sql', 'html', 'css', 'jquery', 'bootstrap', 'mongo-db', 'git', 'web-development', 'data-analytics', 'data-mining', 'data-analysis', 'algorithms', 'text-mining', 'consulting', 'open-source' 'logistic-regression', 'angular-js', 'node-js', 'ajax', 'mongodb', 'react-js', 'open-source', 'big-data', 'hadoop', 'spark' ] @app.route("/", methods=["POST", "GET"]) def home(): if request.method == 'POST' and (request.form['action'] == 'fullstack' or request.form['action'] == 'datascience'): role = request.form['action'] skill_dict = {} skill_dict = model.manual_list(role=request.form['action']) selected_skills = request.form.getlist('check') # if action == # name = request.form['name'] # email = request.form['email'] # phone = request.form['phone'] # fieldnames = ['name', 'email', 'phone'] # with open('nameList.csv','w') as inFile:
from flask import Flask, jsonify, request from flask.ext.sqlalchemy import SQLAlchemy from model import db, init_db, Vote import os app = Flask(__name__) app = init_db(app) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] app.config.from_object('model') app = init_db(app) db.app = app @app.before_first_request def init(): db.create_all() @app.route("/") def index(): #Render static html return app.send_static_file('index.html') @app.route("/supersecurevote", methods=['POST']) def vote(): if request.method == 'POST':
def cli_entry(kafka_address, db_path, debug, host, port): app.debug = debug # "ci.simon-mo.com:32775" config["kafka_addr"] = kafka_address init_db(db_path, debug) uvicorn.run(app, host=host, port=port, debug=debug)
import os import uuid from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from postgresql_event_store import PostgreSQLEventStore, ConcurrentStreamWriteError from order_aggregate import Order from model import init_db pg_host = os.environ.get("PGHOST") pg_database = os.environ.get("PGDATABASE") pg_user = os.environ.get("PGUSER") pg_password = os.environ.get("PGPASSWORD") engine = create_engine(f"postgresql://{pg_user}:{pg_password}@{pg_host}/{pg_database}") init_db(engine) Session = sessionmaker(bind=engine, autocommit=True) session = Session() event_store = PostgreSQLEventStore(session) # order = Order.create(1) # order.set_status("new") # order.set_status("paid") # order.set_status("confirmed") # order.set_status("shipped") # try: # event_store.append_to_stream(order.uuid, order.changes) # except ConcurrentStreamWriteError: # raise Exception("Can't write")
if session.get('isLogin') is None: # redirect to login page return redirect('/login?from=' + request.path) @app.errorhandler(404) def page_not_found(err): """customized 404 page""" return render_template('error-404.html') @app.route('/about') def about(): return render_template('about.html') # register function for Jinja app.jinja_env.globals.update(get_summary=get_summary) app.jinja_env.globals.update(type_to_str=type_to_str) if __name__ == '__main__': app.app_context().push() init_db(app) app.register_blueprint(auth) app.register_blueprint(ueditor) app.register_blueprint(message) app.register_blueprint(comment) app.register_blueprint(profile) app.register_blueprint(search) app.run(debug=True)
def setUp(self): self.db_fd, main.app.config['DATABASE'] = tempfile.mkstemp() main.app.config['TESTING'] = True self.app = main.app.test_client() model.init_db()