def main(): if not 'visits.db' in os.listdir(): db.create_all() if PyQt_on: thread = threading.Thread(target=run_flask_app) thread.daemon = True thread.start() while not url_ok("127.0.0.1", 5000): sleep(0.1) qt_app = QApplication([]) qt_app.setWindowIcon(QtGui.QIcon("brain.ico")) qt_app.setApplicationName("Рассеянный склероз: тесты/опросники") w = QWebEngineView() #w = QWebView() w.load(QUrl('http://127.0.0.1:5000')) w.page().profile().downloadRequested.connect(_downloadRequested) w.show() qt_app.exec_() else: url = 'http://localhost:5005/' webbrowser.open_new_tab(url) app.run(debug=True, port=5005)
def signup(): form = SignupForm() if form.validate_on_submit(): existing_user = Author.query.filter_by(username=form.username.data).first() if existing_user is None: author = Author(username=form.username.data) author.set_password(form.password.data) session['logged_in'] = True session['username'] = author.username db.session.add(author) db.session.commit() # Create new user session['id'] = author.id login_user(author) # Log in as newly created user return redirect(url_for('index')) flash('A user already exists with that username.') return render_template( 'register.html', title='Create an Account.', form=form, body="Please Sign Up!" ) if __name__ == "__main__": app.run()
Factory_Stalk_Collection.date_fulfilment == None, Factory_Stalk_Collection.state == g.user[0:2], Factory_Stalk_Collection.district_name == g.district) return render_template('/factory_manager/index.html', c_list=complete_list) else: return render_template('404.html') @app.route('/factory_manager/report_generation/', methods=['GET', 'POST']) def report_generation(): if g.user and g.user[4] == 'M': return render_template('/factory_manager/report_generation.html') else: return render_template('404.html') @app.route('/factory_manager/todays_collection/', methods=['GET', 'POST']) def todays_report(): if g.user and g.user[4] == 'M': todays_list = Factory_Stalk_Collection.query.filter_by( date_fulfilment=now.strftime("%Y/%m/%d")) return render_template('/factory_manager/todays_collection.html', t_list=todays_list) else: return render_template('404.html') if __name__ == '__main__': app.run(debug=True, host="0.0.0.0")
return redirect(url_for('login')) return render_template('register.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] user = User.query.filter_by(email=email).first() if user: if bcrypt.check_password_hash(user.password, password): login_user(user) flash('Logged in successfully.') return redirect(url_for('departments')) flash('Credentials dont match') return redirect(url_for('register')) return render_template('login.html') @login_required @app.route('/logout', methods=['GET']) def logout(): logout_user() return redirect(url_for('login')) if __name__ == '__main__': db.create_all() app.run(host='0.0.0.0', port=5000, debug=True)
) statement_view = StatementApiEndpoint.as_view('statement_api') app.add_url_rule(statement_view.view_class.url_stem, defaults={'id': None}, view_func=statement_view, methods=['GET',]) app.add_url_rule('/statement/<int:id>', view_func=statement_view, methods=['GET',]) def has_no_empty_params(rule): defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments) #api.add_resource(DebatesApiEndpoint, '/index') @app.route("/") def site_map(): #http://stackoverflow.com/questions/13317536/get-a-list-of-all-routes-defined-in-the-app links = [] for rule in app.url_map.iter_rules(): # Filter out rules we can't navigate to in a browser # and rules that require parameters if "GET" in rule.methods and has_no_empty_params(rule): url = url_for(rule.endpoint, _external = True, **(rule.defaults or {}) ) links.append({rule.endpoint: url}) # (url,rule.endpoint)) # links is now a list of url, endpoint tuples return jsonify({'_items': links}) app.run(debug=True, use_reloader=True)
# 只展示当前用户才能看到的内容 user = User.query.filter_by(account=session["user"]).first() user_id = user.id page_data = Article.query.filter_by(user_id=user_id).order_by( Article.add_time.desc()).paginate(page=page, per_page=1) #使用数据库中保存的category数字在categorylist中取到对应的索引位置的元组 category = [(1, u"科技"), (2, u"搞笑"), (3, u"军事")] return render_template("art_list.html", title="文章列表", page_data=page_data, category=category) # 验证码 @app.route("/captcha/", methods=["GET"]) def captcha(): from captcha import Captcha c = Captcha() info = c.create_captcha() image = os.path.join(os.path.dirname(__file__), "static/captcha") + "/" + info["image_name"] with open(image, 'rb') as f: image = f.read() session['captcha'] = info["captcha"] # print(session['captcha']) return Response(image, mimetype="jpeg") if __name__ == "__main__": app.run(debug=True, host="127.0.0.1", port=5000)
nodes = conf['cluster']['nodes'].split() node = conf[get_local_hostname()] http_port = node.get('http_port', 9999) if 1 < len(sys.argv): http_port = sys.arv[1] # for node in Node.query.all(): # node.status = NodeStatus.NA # db.session.commit() # local_ip = get_local_ip() # nodes = Node.query.filter_by(ip=local_ip) # node = None # if (1 == nodes.count()): # node = nodes.first() # else: # node = Node(ip=local_ip, hostname=get_local_hostname() or '') # db.session.add(node) # node.refresh() # db.session.commit() # tasks = [] # t_refresh = Thread(target=node.refresh) # tasks.append(t_refresh) # for task in tasks: # task.start() app.run(debug=True, use_reloader=True, host='0.0.0.0', port=http_port)
return app.send_static_file("index.html") @app.route('/<path:path>') def static_proxy(path): # Send files from directory ./static/ if os.path.exists('./static/' + path): return app.send_static_file(path) else: return app.send_static_file('index.html') if __name__ == "__main__": # Wait until the database is running db_down = True if 'debug' in sys.argv: app.config["SQLALCHEMY_DATABASE_URI"] = DEBUG_DATABASE_URI else: while db_down: try: psycopg2.connect(SQLALCHEMY_DATABASE_URI).close() db_down = False except: time.sleep(1) continue # Create any missing tables db.create_all() # Start server app.run(host="0.0.0.0", port=8000)
config = config.one() config.update(request.json) except NoResultFound: config = Config(user, request.json) db.session.add(config) db.session.commit() return _json_response(config.json()) elif request.method == "DELETE": try: db.session.delete(config.one()) db.session.commit() except NoResultFound: pass return Response(status=200) elif request.method == "GET": return _json_response(config.first_or_404().json()) @app.route("/user/<uid>/<cid>") def user_item(uid, cid): config = Config.query.filter(Config.user_id == uid).filter(Config.id == cid) return _json_response(config.first_or_404().json()) if __name__ == "__main__": # debug settings app.config["SECRET_KEY"] = "debugkey" db.create_all() app.run(host="localhost", port=5000, debug=True)
def main(): db.create_all() #secret key shoould be very strong app.secret_key = 'My Secret' app.run(debug=True, port=8080)
def update_session(user): session['logged_in'] = True session['username'] = user.email session['first_name'] = user.fname session['userid'] = user.userid user = models.get_user_by_id(session['userid']) session['userid'] = user.userid cust = models.get_customer_by_user(user) chef = models.get_chef_by_user(user) if (cust): session['custid'] = cust.customerid else: session['custid'] = None if (chef): session['chefid'] = chef.chefid else: session['chefid'] = None # END update_session if __name__ == '__main__': app.run(host="0.0.0.0", port=5050, debug=True) #app.run(host = "127.0.0.1", port = 5050, debug = True)
if forms.validate_on_submit(): file_dir = get_uploaddir() f = request.files['uploadfile'] # 从表单的file字段获取文件,myfile为该表单的name值 if f and allowed_file(f.filename): # 判断是否是允许上传的文件类型 fname = f.filename ext = fname.rsplit('.', 1)[1] # 获取文件后缀 #unix_time = int(time.time()) fn = datetime.now().strftime('%Y%m%d%H%M%S') fn = fn + '_%d' % random.randint(0, 100) new_filename = fn + '.' + ext # 修改文件名 f.save(os.path.join(file_dir, new_filename)) # 保存文件到upload目录 att = Attatch() att.sourcename = secure_filename(fname) att.todo_id = todo_id att.own_id = session.get('user_id') att.filepath = new_filename db.session.add(att) db.session.commit() flash("上传附件成功", 'ok') return redirect(url_for('edit', page=page, id=todo_id)) else: flash("上传失败", 'error') return redirect(url_for('edit', page=page, id=todo_id)) else: return render_template('upload.html', forms=forms) if __name__ == '__main__': app.run(port='9000')
from os import environ from models import app if __name__ == '__main__': HOST = environ.get('SERVER_HOST', 'localhost') try: PORT = int(environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.debug = True app.run(HOST, PORT)
return redirect('https://www.google.com/search?q=404') @app.errorhandler(500) def ISE(request): return 'Oopsy daisy. Something went wrong.' @app.teardown_request def shutdown_session(exception=None): db.session.remove() def regmatch(urlinput, isPresent = re.compile(r'[^a-z0-9_]').search): return not bool(isPresent(urlinput)) def custompost(): medium = True try: if User.query.filter_by(password = request.form['password']).first(): pass else: medium = False except: medium = False return medium if __name__ == "__main__": app.run(debug = False)
if not word: return "<div>Please input keyword!</div>" keywords = Keyword.objects.filter(word=word) if keywords: keyword = keywords[0] else: keyword = Keyword(word=word) domain = whois.query("%s.com" % str(word)) keyword.website = {"exist": bool(domain)} for platform in PLATFORMS: keyword.__setattr__(platform, {"exist": fetch(platform, word)}) keyword.save() platforms = dict((key, keyword.__getattribute__(key)) for key in PLATFORMS) platforms["website"] = keyword.website return render_template("result.html", platforms=platforms) @app.route("/keywords/<word>", methods=["GET"]) def get_keyword_detail(word): keywords = Keyword.objects.filter(word=word) if not keywords: return page_not_found("") keyword = keywords[0] platforms = dict((key, keyword.__getattribute__(key)) for key in PLATFORMS) platforms["website"] = keyword.website return render_template("keyword.html", keyword=keyword, platforms=platforms) if __name__ == "__main__": app.run(host="0.0.0.0", port=8997, debug=True)
'Average total time in A+E (minutes)'] # each row is for a hospital rows = [] for place in places: row = {} row['name'] = place.name row['id'] = place.id rating = Rating.query.filter_by(place=place).first() row['cleanliness'] = rating.cleanliness row['staff']= rating.staff_worked_well row['dignity'] = rating.dignity_respect row['involved'] = rating.involved_with_decision safety = PatientSafety.query.filter_by(place=place).first() row['safety'] = safety place_services = PlaceServices.query.filter_by(place=place).first() if place_services is None: row['number_of_services'] = None else: # we need to make sure this service is offered, so only count it if # the value is true row['number_of_services'] = len( [service for service in place_services.services if service.value]) waiting_times = WaitingTimes.query.filter_by(place=place).first() row['waiting_times'] = waiting_times rows.append(row) return render_template('compare.html', rows=rows, headers=headers) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
text = request.form['text'] # recording uploads filename = '' rec_file = request.files['rec_file'] if rec_file.filename == '': flash('Nop Selectd file') return redirect(request.url) if rec_file and allowed_file(rec_file.filename): filename = secure_filename(rec_file.filename) rec_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) recording_path = '%s/%s' % (file_path, filename) save_recording_file_url = '%s/uploads/%s' % (prefix, filename) rec_text = run_google_api(recording_path) comparison = str(SequenceMatcher(None, text, rec_text).ratio() * 100) ret['Comparison_percentage'] = comparison ret['success'] = True except Exception as exp: print 'matching_test() :: Got Exception: %s' % exp print(traceback.format_exc()) ret['msg'] = '%s' % exp ret['success'] = False return jsonify(ret) if __name__ == '__main__': port = int(os.environ.get('PORT', 8080)) context = ('server.crt', 'server.key') app.run(host='0.0.0.0', port=port, debug=True, threaded=True)
from flask import Flask from flask import request import hashlib from models import db, User, app @app.route('/api/users/create', methods=['POST']) def createUser(): data = {} data['username'] = request.args.get('username') users = User.query.filter(User.username == data['username']) if (len(users.all()) > 0): return "User already exists" data['email'] = request.args.get('email') passwordU = request.args.get('password') data['password'] = hashlib.sha1(passwordU).hexdigest() user = User(data) db.session.add(user) db.session.commit() return str(user.id) if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0')
for elem in people: peoplelist.append(elem.idtype + ": " + str(elem.id)) return json.dumps(peoplelist) @app.route('/add', methods=['POST']) def new(): data = request.form['data'] data = json.loads(data) a = gsm(data['id'], 4444, datatime.datetime.now(), 200, data['method'], data['name'], data['dob'], data['e-number']) db.session.add(a) db, session.commit() #name, dob, e-name, e-number, cond, medicines, id, method @app.route('/') def index(): trackers = tracker.query.all() trackerlist = {} for elem in trackers: trackerlist[int(elem.trackernumber)] = elem.location.encode( 'ascii', 'ignore') print trackerlist return render_template('index.html', tracker=trackerlist) if __name__ == "__main__": app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.run(host="0.0.0.0", port=8000, debug=True)
from models import app, db import views if __name__ == '__main__': with app.app_context(): db.create_all() print app.url_map app.run(debug=True)
from flask import Flask from todo import main as todo_routes from api import main as api_routes from models import app # app = Flask(__name__) # app.secret_key = 'random string' # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.register_blueprint(todo_routes) app.register_blueprint(api_routes, url_prefix='/api') if __name__ == '__main__': config = dict( debug=True, host='0.0.0.0', port=2000, ) app.run(**config)
gdata = {'pname':png1w, 'gname':dsname, 'rrdpath':rpath, 'pitem':dss, 'unit':unit, 'cols':'', 'itypes':'', 'host':hostname, 'stime':strtime, 'flag':'Weekly'} gdatas.append(gdata) ########################### strtime = str(int(time.time()- 2592000)) gdata = {'pname':png1m, 'gname':dsname, 'rrdpath':rpath, 'pitem':dss, 'unit':unit, 'cols':'', 'itypes':'', 'host':hostname, 'stime':strtime, 'flag':'Monthly'} gdatas.append(gdata) ########################### strtime = str(int(time.time()- 31536000)) gdata = {'pname':png1y, 'gname':dsname, 'rrdpath':rpath, 'pitem':dss, 'unit':unit, 'cols':'', 'itypes':'', 'host':hostname, 'stime':strtime, 'flag':'Yearly'} gdatas.append(gdata) ########################## #print gdatas,'---',pngs for gdata in gdatas: #if os.path.isfile(gdata['pname']): os.remove(gdata['pname']) print "----graphing ",gdata['pname'] if len(gdata['pitem']) == 1: graphsub.dItem01(gdata) if len(gdata['pitem']) == 2: graphsub.dItem02(gdata) if len(gdata['pitem']) == 3: graphsub.dItem03(gdata) if len(gdata['pitem']) == 4: graphsub.dItem04(gdata) if len(gdata['pitem']) == 5: graphsub.dItem05(gdata) if len(gdata['pitem']) == 6: graphsub.dItem06(gdata) if len(gdata['pitem']) == 7: graphsub.dItem07(gdata) return render_template('drawall.html', pngs=pngs) if __name__ == "__main__": app.run(host="0.0.0.0", port=5001, debug=True)
app.logger.error("Garbage collector failed for container id {0} from node {1}".format(con.container_id, con.node.ip_addr)) except Exception as e: app.logger.exception("Garbage collector received exception while reaping containers\n{0}".format(e)) def health_monitor(): while True: try: monitor_server_health() monitor_container_health() container_garbage_collector() except Exception as e: app.logger("Monitor thread received unhandled exception. {0}".format(e)); sleep(HEALTH_CHECK_INTERVAL) if __name__ == '__main__': if not os.path.isfile(db_file_name): create_db_schema() insert_default_entries(db) #test_suite(con_manager) """ node_status_thread = threading.Thread(target=monitor_server_health) node_status_thread.start() container_status_thread = threading.Thread(target=monitor_container_health) container_status_thread.start() garbage_collector_thread = threading.Thread(target=container_garbage_collector) garbage_collector_thread.start() """ monitor_thread = threading.Thread(target=health_monitor) monitor_thread.start() app.run(host="0.0.0.0", debug=True, use_reloader=False)
def chat(): """ chat end point that performs NLU using rasa.ai and constructs response from response.py """ message = request.form["text"] print(message) response = send_message(message) if response["status"]["code"] == 200: reply_message = response["result"]["fulfillment"]["speech"] try: intent, action, entitiy = get_intent_action_entity(response) except KeyError: pass print(intent, entitiy, action) if action: try: methodToCall = getattr(action_methods, action) outcome = methodToCall(entitiy) print("$$$$$$$$$$$$", outcome) reply_message = format_message(action, reply_message, outcome) except AttributeError: pass print(reply_message) return jsonify({"status": "success", "response": reply_message}) app.config["DEBUG"] = True if __name__ == "__main__": app.run(port=5000)
@app.route('/query', methods=['POST']) def query(): trackerid = request.form['id'] people = gsm.query.filter_by(tracker=int(trackerid)).all() peoplelist = [] for elem in people: peoplelist.append(elem.idtype + ": " +str(elem.id)) return json.dumps(peoplelist) @app.route('/add', methods=['POST']) def new(): data = request.form['data'] data = json.loads(data) a = gsm(data['id'],4444,datatime.datetime.now(),200,data['method'],data['name'],data['dob'],data['e-number']) db.session.add(a) db,session.commit() #name, dob, e-name, e-number, cond, medicines, id, method @app.route('/') def index(): trackers = tracker.query.all() trackerlist = {} for elem in trackers: trackerlist[int(elem.trackernumber)] = elem.location.encode('ascii', 'ignore') print trackerlist return render_template('index.html',tracker = trackerlist) if __name__ == "__main__": app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.run(host="0.0.0.0", port=8000,debug=True)
#if you are assignee, assigner list of task contents, list of fb_id of #everyone assigned. return render_template('home.html', me=me, app=app, friends=friends, user_assigned=user_assigned_tasks, assigned_to_user=assigned_to_user) @app.route('/permalink/<path:ajax_path>') def permalink(ajax_path): return root(render_template('permalink_load.html', ajax_path=ajax_path)) @app.route('/experiment/piglatin/', methods=['GET', 'POST']) def pig(): def piglatin(inp): if len(inp) < 3: return inp+"ay" else: return inp[1:]+inp[0]+"ay" inp = request.args.get('inp', None) return render_template('experiment.html', out=piglatin(inp)); if __name__ == '__main__': port = int(os.environ.get("PORT", 5000)) if app.config.get('FBAPI_APP_ID') and app.config.get('FBAPI_APP_SECRET'): app.run(host='0.0.0.0', port=port) else: print 'Cannot start application without Facebook App Id and Secret set'
def get_all_from_category(table): """ Helper that gets all data from a given table """ data = db.session.query(table).all() return json.dumps(list(map(lambda d: d.dictionary(), data))) @app.errorhandler(404) def page_not_found(error): """ returns a 404 page """ return render_template('404.html', alt_title=error, error=error) @app.route('/run_tests') def run_tests(): """ runs the tests and returns the output :return: the json with results """ output = subprocess.getoutput("python startupfairy/tests.py") return json.dumps({'test_results': str(output)}) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=80)
PresenceIn(hospital_id=int(hospital_id), vacc_id=int(vacc_id), num_present=int(num_present))) db.session.commit() def load_csv_abroad(): with open('./data/abroad.csv') as f: line, lines = f.readline(), f.readlines() for line in lines: name, vacc_id = line.strip().split(sep=',') cli = ForeignCountries.query.filter_by(name=name, vacc_id=int(vacc_id)) if not cli: db.session.add(ForeignCountries(name=name, vacc_id=int(vacc_id))) db.session.commit() if __name__ == '__main__': db.create_all() # load_csv_abroad() # load_csv_hospitals() # load_csv_vaccines() # load_csv_age_vaccines() # load_csv_presence_in() load_csv_hospitals() app.run(debug=True, port=4000)
project = Project.query.get_or_404(id) if request.form: project.created = datetime.datetime.strptime(request.form['date'], "%Y-%m") project.title = request.form['title'] project.description = request.form['desc'] project.skills = request.form['skills'] project.url = request.form['github'] db.session.commit() print(project) return redirect(url_for('index')) return render_template('edit.html', projects=all_projects, project=project) @app.route('/project/<id>/delete') def delete(id): project = Project.query.get_or_404(id) db.session.delete(project) db.session.commit() return redirect(url_for('index')) @app.errorhandler(404) def not_found(error): return render_template("404.html", msg=error), 404 if __name__ == '__main__': db.create_all() app.run(debug=True, port=8000, host='127.0.0.1')
from models import app, db, User from flask import jsonify, request, redirect, url_for @app.route('/') def home(): return jsonify(message="Welcome to my api") @app.route('/users', methods=['GET', 'POST']) def user_index_create(): if request.method == "GET": # get all users in db users = User.query.all() if len(users) > 0: print(type(users[0])) results = [user.to_dict() for user in users] return jsonify(results) else: return 'no users found' if request.method == "POST": new_user = User(name=request.form['name'], email=request.form['email'], bio=request.form['bio']) db.session.add(new_user) db.session.commit() print(new_user) return jsonify(new_user.to_dict()) if __name__ == '__main__': app.run('localhost', 5000, debug=True)
def server_error(error): '''Displays Error Page in case of a 500 error Corresponding HTML: - templates/errors/500.html ''' return render_template('errors/500.html'), 500 if not app.debug: # if app is not in debug mode, fill error.log file_handler = FileHandler('error.log') file_handler.setFormatter( Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('errors') #----------------------------------------------------------------------------# # Launch. #----------------------------------------------------------------------------# # Run App with Default port. Debug Mode set in config.py if __name__ == '__main__': app.run(debug=app.debug ) # NOTE I prefer to set debug mode to true within the script
from datetime import datetime from flask import request, render_template, redirect from models import db, app, Tasks, Results @app.route("/") def hello(): address = request.args.get('address') results = Results.query.all() if address: address = address.strip() if not address.startswith('http://') and not address.startswith( 'https://'): address = 'http://' + address task = Tasks(address=address, task_status='NOT_STARTED', timestamp=datetime.now()) db.session.add(task) db.session.commit() return redirect('/') return render_template('index.html', results=results) if __name__ == "__main__": db.create_all() app.run(debug=False, host='0.0.0.0', port=5000)
from flask import (Flask, redirect, url_for, render_template) from models import app from views.manufac import manufac_blueprint from views.products import prod_blueprint from views.people import person_blueprint from views.settings_modif import settings_blueprint {{IMPORTS}} app.register_blueprint(manufac_blueprint) app.register_blueprint(prod_blueprint) app.register_blueprint(person_blueprint) app.register_blueprint(settings_blueprint) {{REGISTER_BLUEPRINTS}} @app.route('/') def index(): return redirect('/manufac/') if __name__ == '__main__': app.run(debug=True, host='127.0.0.1')
@app.route('/user/<int:user_id>/note/<int:note_id>/delete/', methods=["GET", "POST"]) def delete__note(user_id, note_id): user = User.query.filter_by(id=user_id).first() note = Note.query.filter_by(id=note_id, user_id=user_id).first() if request.method == "POST": delete_note(note) return redirect(url_for('user_bag', user_id=user.id)) return render_template('delete_note.html', note=note, user=user) @app.route('/users/api/') def users(): if current_user.email == "*****@*****.**": users = User.query.all() users_ls = [] for user in users: users_ls.append({"email": user.email, " name": user.name}) return jsonify({"users": users_ls}) else: return "badddd" if __name__ == "__main__": app.run(debug=app.config['DEBUG'])
if len(line) > 1: Stop = VBB_Stop(line) if "(Berlin)" in Stop.name: feedback = Stop.is_in_osm() if feedback > 0: print_success(Stop.name + ": " + str(feedback)) else: print_failure(Stop.name + ": 0") new_stop = DB_Stop( name = Stop.name, lat = Stop.lat, lon = Stop.lon, matches = feedback, vbb_id = Stop.stop_id ) db.session.add(new_stop) db.session.commit() def print_success(message): ''' Print the message in green ''' print '\033[1;32m%s\033[1;m'% (message) def print_failure(message): ''' Print the message in red ''' print '\033[1;31m%s\033[1;m'% (message) if __name__ == "__main__": app.debug = True app.run()
query = request.args.get('query') return search(City, query) @app.route('/api/search/snapshots') def search_snapshots(): query = request.args.get('query') return search(Snapshot, query) # serve the React app @app.route('/', defaults={'path': ''}) @app.route("/<string:path>") @app.route('/<path:path>') def serve_react(path): if path != "": if os.path.exists(os.path.join(REACT_FILES, 'index.html')): return send_from_directory(REACT_FILES, path) else: return send_from_directory(REACT_FILES, 'index.html') else: return send_from_directory(REACT_FILES, 'index.html') # run on port 5000 if __name__ == '__main__': print('*** STARTING APPLICATION ***') app.run(port=5000, use_reloader=True, threaded=True)
from models import app if __name__ == "__main__": app.run()
@app.before_first_request def initialize(): db.create_all() @app.route("/btlshp/<address>") def add_to_database(address): players = Player.query.all() if (len(players) % 2 == 1): last = Player.query.order_by(Player.id.desc()).first() gc = last.game_contract else: gc = deploy_contract(game_contract) randomseed = hex(random.randint(1, 2**128))[2:] player = Player(address=address, game_contract=gc, randomseed=randomseed) db.session.add(player) db.session.commit() return Response(json.dumps({ 'address': gc, 'abi': game_contract['abi'], 'salt': randomseed }), status=200, mimetype='application/json') if __name__ == "__main__": app.run(port=8000, debug=True, host="127.0.0.1")
@app.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page = request.args.get('next') return redirect(next_page) if next_page else redirect(url_for('home')) else : flash('Login Gagal. Silahkan Periksa Kembali Email dan Password', 'danger') return render_template('login.html', title='Login', form=form) @app.route('/logout') def logout(): logout_user() return redirect(url_for('home')) @app.route('/account') @login_required def account(): return render_template('account.html', title='Account') if __name__ =='__main__' : app.run(debug=True)
@login_manager.user_loader def load_user(user_id): user = controller.query_user(int(user_id)) if user: return DbUser(user) else: return None @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) identity.provides.add(UserNeed(current_user.get_vendor_code())) # Assuming the User model has a list of roles, update the # identity with the roles that the user provides if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
strtime = str(int(time.time() - 31536000)) gdata = { 'pname': png1y, 'gname': dsname, 'rrdpath': rpath, 'pitem': dss, 'unit': unit, 'cols': '', 'itypes': '', 'host': hostname, 'stime': strtime, 'flag': 'Yearly' } gdatas.append(gdata) ########################## #print gdatas,'---',pngs for gdata in gdatas: #if os.path.isfile(gdata['pname']): os.remove(gdata['pname']) print "----graphing ", gdata['pname'] if len(gdata['pitem']) == 1: graphsub.dItem01(gdata) if len(gdata['pitem']) == 2: graphsub.dItem02(gdata) if len(gdata['pitem']) == 3: graphsub.dItem03(gdata) if len(gdata['pitem']) == 4: graphsub.dItem04(gdata) if len(gdata['pitem']) == 5: graphsub.dItem05(gdata) if len(gdata['pitem']) == 6: graphsub.dItem06(gdata) if len(gdata['pitem']) == 7: graphsub.dItem07(gdata) return render_template('drawall.html', pngs=pngs) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000)
from flask import Flask from flask import request import hashlib from models import db, User, app @app.route('/api/users/create', methods = ['POST']) def createUser(): data = {} data['username'] = request.args.get('username') users = User.query.filter(User.username == data['username']) if (len(users.all()) > 0): return "User already exists" data['email'] = request.args.get('email') passwordU = request.args.get('password') data['password'] = hashlib.sha1(passwordU).hexdigest() user = User(data) db.session.add(user) db.session.commit() return str(user.id) if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0')