def main(): app = Flask(__name__) manager = TariffManager() my_online = Tariff('Мой Онлайн', hit=True, gb=15, minutes=400, gb_unlim=['vk', 'fb'], price=290) my_tele2 = Tariff('Мой Теле2', price=7, price_period='day', gb=6) univer = Tariff('Универ', archived=True) manager.add(my_online) manager.add(my_tele2) manager.add(univer) @app.route('/', methods=['GET', 'POST']) def actual(): actual_tariff = manager.actual() result = [] for item in actual_tariff: result.append(manager.create_dic(item)) return render_template('ind.html', result=result) @app.route('/archive') def archive(): archive_tariff = manager.archived() result = [] for item in archive_tariff: result.append(manager.create_dic(item)) return render_template('arch.html', result=result) app.run(port=9876, debug=True)
def main(): app.run(debug=True) # Serving the favicon with app.app_context(): app.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon/favicon.ico'))
def run(game_): global game if game_: game = game_ #print("Starting server") app.run() else: raise Exception('Game is Undefined')
def start(target, port, env): if not param_check(target, port, env): return handler = handler_dict[target] watcher = handler.watcher @app.route('/deal_{}_message'.format(target), methods=['POST']) def deal(): try: start = time.time() request_ip = request.remote_addr if request_ip in ACL: message_list = json.loads(request.get_data()) mess_len = len(message_list) if message_list: watcher.timer("{}_message_once_ready_count".format(target), mess_len) handler.deal_messages(message_list, watcher, start) logger.info("module [{}] port [{}] deal ok , message [{}]".format(target, port, json.dumps(message_list))) return json.dumps({"success":True,"code":200,"message":""}) else: logger.info( "module [{}] port [{}] service failed, empty request".format(target, port)) return json.dumps({"success":False,"code":400,"message":"empty request"}) else: logger.info("module [{}] port [{}] service failed, ip {} not allowd".format(target, port, request_ip)) return json.dumps({"success":False,"code":403,"message":"bad request, ip not allowed"}) except Exception: logger.error("module [{}] port [{}] service error, info {}".format(target, port, error_info())) return json.dumps({"success":False,"code":500,"message":error_info()}) @app.route('/healthcheck', methods=['GET', 'POST']) def check(): logger.info("healthcheck pass") return 'ok' @app.before_first_request def init(): zk.start() zk.create('/{}/{}/{}/'.format(zk_app_name, zk_module_name_web, target), '{}:{}'.format(socket.gethostbyname(socket.gethostname()), port).encode(), ephemeral=True, sequence=True, makepath=True) logger.info("module [{}] port [{}] register on zookeeper".format(target, port)) try: app.run(port=int(port), debug=False, host='0.0.0.0') except: logger.error("[{}] [{}] start error".format(target, port), error_info) try: zk.stop() except: logger.error(error_info) pass
class API(): app = Flask(__name__) app.run(host='0.0.0.0', port='5002') def flask_api(self, json, url_v_one): # app = Flask(__name__) @app.route('/<carname>', methods=['GET']) def run_flask(carname, json): print carname return json
def gen(): cv2.imwrite('t.jpg', hsv) yield (b'--hsv\r\n' b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n') print('''<script>let videopython='{0}';</script>'''.format(hsv)) print('''var videopython = document.querySelector('videopython');''') print( '''<style>videopython {background: #222;margin: 0 0 20px 0;width: 100%;} videopython { object-fit: cover;} @media (min-width: 1000px) {videopython {height: 480px;}}</style><videopython autoplay playsinline></videopython></body></html>''' ) @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=hsv') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True, ssl_context=('/var/security/lftr.biz.crt', '/var/security/lftr.biz.key'), port=8080, threaded=True)
app = Flask(__name__) bootstrap = Bootstrap(app) # use jQuery2 instead of jQuery 1 shipped with Flask-Bootstrap app.extensions['bootstrap']['cdns']['jquery'] = WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/') @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/', methods=['GET']) def index(): return render_template('index.html') # return a json response upon request @app.route('/rand', methods=['GET']) def rand(): # 't' is defined in javascript t = request.args.get('t', 0, type=int) # n here is random, but can of course be query result in a database n = random.random() return jsonify(result = n) if __name__ == '__main__': app.run(debug = True)
format_string += "%s (similarity:%.5f%)<BR>" % ( top_names[i], scores[i] * 100) format_string += '\n' return new_tag + format_string + '<BR>' return redirect(url_for('classifier_predict')) if __name__ == '__main__': app.debug = False model_id = sys.argv[1] model_file = sys.argv[3] label_file = sys.argv[4] # image_file = sys.argv[5] port = sys.argv[2] graph = tf.Graph() with graph.as_default(): classify_graph_def = tf.GraphDef() print('classify_graph_def = tf.GraphDef()') with tf.gfile.GFile(model_file, 'rb') as f: # with open(model_file, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') sess = tf.Session(graph=graph) app.run(host='0.0.0.0', port=port, debug=False) # global model_id # model_id = 5 # app.run(host='0.0.0.0', port="3444") run_inference_on_image('./slim/test.jpg', sess)
elif request.method == 'GET': try: name = user_info(id) return {'status': 'ok', 'user name': name}, 200 except: return {'status': 'error', 'reason': "no such id"}, 500 elif request.method == 'DELETE': try: delete_user_id(id) return {'status': 'ok', 'user deleted': id}, 200 except: return {'status': 'error', 'reason': "no such id"}, 500 elif request.method == 'PUT': try: name = request.json.get('user_name') update_username(id, name) return {'status': 'ok', 'user updated': id}, 200 except: return {'status': 'error', 'reason': "no such id"}, 500 @app.route('/stop_server') def stop_server(): os.kill(os.getpid(), signal.SIGINT) return 'Server stopped', 200 app.run(host='127.0.0.1', debug=True, port=5000)
@app.route('/<path:path>') def send_js(path): return send_from_directory('frontend/src', path) @app.route("/ListRoutes", methods=['GET']) @jsonp def ListRoutes(): routes = [] for rule in app.url_map.iter_rules(): routes.append('%s' % rule) return jsonify(success=True, routes=[e for e in routes]) @app.route("/config_files", methods=['GET']) @jsonp def config_files(): return jsonify(success=True, logfile=logfile, config_file=config_file, ad_file=ad_file, domain_config_file=domain_config_file, sqlite_cache_file=sqlite_cache_file) if __name__ == "__main__": #app.run(ssl_context='adhoc', debug=True, host='0.0.0.0', port=9990) app.run(debug=True, host='0.0.0.0', port=port)
from flask import app from muhu_project import create_app app = create_app() if __name__ == "__main__": app.run('localhost', 5555)
else: form = MyForm(csrf_enabled=False) resp = make_response(render_template("form.html", form=form)) return resp @app.route('/pwchange.html', methods=['GET', 'POST']) def changepw(): form = MyForm(csrf_enabled=False) resp = make_response(render_template("pwchange.html", form=form)) return resp @app.route('/management.html', methods=['GET', 'POST']) def management(): form = MyForm(csrf_enabled=False) resp = make_response(render_template("management.html", form=form)) return resp @app.route('/punches.html', methods=['GET', 'POST']) def punches(): form = MyForm(csrf_enabled=False) resp = make_response(render_template("punches.html", form=form)) return resp htm_open = '<html><body bgcolor="#2b2b2b"><center><i><font color="gray">clockpunch</font></i><br><br><font color="white"><b>' htm_close = '</b></font></center></body></html>' app.run(host='0.0.0.0', port=80)
def start_game(): webbrowser.open("http://127.0.0.1:5000/") app.run()
print im1_feature feature1 = [float(item) for item in im1_feature.split(',')[:-1]] feature2 = [float(item) for item in im2_feature.split(',')[:-1]] try: dist = np.sqrt(np.sum(np.square(np.subtract(feature1, feature2)))) if dist < 0.6: code = '200' pass_value = 'Yes' else: code = '500' pass_value = 'No' data = {'code': code, 'pass': pass_value} result = json.dumps(data) return result except: data = {'code': '500', 'pass': '******'} result = json.dumps(data) return result else: data = {'code': '500', 'feature': 'non living body, try again'} result = json.dumps(data) return result if __name__ == '__main__': app.run(host='0.0.0.0', port=6175, debug=False)
# _____ _ _ _ _ # | ____|_ __ _ __ ___ _ __ | | | | __ _ _ __ __| | | ___ _ __ ___ # | _| | '__| '__/ _ \| '__| | |_| |/ _` | '_ \ / _` | |/ _ \ '__/ __| # | |___| | | | | (_) | | | _ | (_| | | | | (_| | | __/ | \__ \ # |_____|_| |_| \___/|_| |_| |_|\__,_|_| |_|\__,_|_|\___|_| |___/ @app.errorhandler(404) def page_not_found(e): return render_template('errors/404.html'), 404 @app.errorhandler(403) def forbidden(e): return render_template('errors/403.html'), 403 @app.errorhandler(500) def server_error(e): # if not app.debug: # send_email('*****@*****.**', 'It\'s reprogramming time!', # "<a href=\"https://youtu.be/QDSEpjjavhY?t=182\">It's reprogramming time!</a><br/>An error was detected on your server: {}".format(e), # '*****@*****.**', PROJECT_PASSWORD) return render_template("errors/500.html"), 500 if __name__ == "__main__": app.debug = True # toolbar=DebugToolbarExtension(app) app.run(host="0.0.0.0")
setattr(obj, key, None) else: setattr(obj, key, value) obj.current_user_id = current_user.id return obj # endregion # region run server if __name__ == '__main__': port = 5200 ip = "0.0.0.0" if (settings.LINUX_OS): print("linux start ok.") app.run(debug=False, host=ip, port=port, use_reloader=False, threaded=True) if (settings.WINDOWS_OS): print("windows start ok.") app.run(debug=True, host=ip, port=port, use_reloader=True, threaded=True) # endregion
response.headers.add('Access-Control-Allow-Methods', 'POST') response.headers.add('Access-Control-Allow-Headers', 'X-Requested-With') return response ################################################################ ################# private backend api ########################### # sample: http://127.0.0.1:9180/api_insert_post # Note: this is an internal api @app.route("/api_insert_post", methods=['POST']) def insert_post(): return "TODO be implemented" def handle_feedback(uid, category, postid, comment, clientip): seconds = int(round(time.time())) dir_name = "%s/%s" % (config.DATA_BASEDIR, category) field_list = ["postid="+postid, "category="+category, "seconds="+str(seconds), "uid="+uid, "comment="+comment, "ip="+clientip] fb_log.info(config.FIELD_SEPARATOR.join(field_list)) ################################################################ if __name__ == "__main__": data.create_db_engine() app.debug = True # Generate a secret random key for the session app.secret_key = os.urandom(24) app.permanent_session_lifetime = timedelta(seconds=10) app.run(host="0.0.0.0", port = int(config.FLASK_SERVER_PORT), threaded=True) ## File : server.py
'period_to': '2017-01-02T00:00:00', }) result.append({'name': 'АнализПервичный_2', 'reference': '/analysis_2', 'type': 'primary', 'period_from': '2017-01-04T00:00:00', 'period_to': '2017-01-07T10:00:00', }) result.append({'name': 'АнализЭкономический', 'reference': '/analysis_3', 'type': 'economical', 'period_from': '2017-01-05T00:00:00', 'period_to': '2017-01-15T00:00:00', }) return Response(response=json.dumps(result), content_type='application/json') @app.route('/GetAnalysisTypes', methods=['GET']) def getAnalysisTypes(): result = [] result.append({'name': 'Первичный', 'id': 'primary'}) result.append({'name': 'Экономический', 'id': 'economical'}) return Response(response=json.dumps(result), content_type='application/json') app.run(host="192.168.150.225", port=8080)
from flask import Flask, request, app, g import sqlite3 app = Flask(__name__) @app.before_request def before_request(): g.db = sqlite3.connect("music.db") @app.teardown_request def teardown_request(exception): if hasattr(g, 'db'): g.db.close() @app.route('/artist') def artist(): artist = g.db.execute("SELECT name FRIM artist").fetchall() return render_template('artist.html', artist = artist) db.execute('SELECT * FROM artist').fetchall() if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
resp = make_response(return_j, 200) resp.headers['Content-Type'] = "application/json" resp.headers['Access-Control-Allow-Origin'] = "*" return resp @app.route('/add_enforced_connection', methods=['POST']) def add_enforced_connection(): print("enforcing a new connection") j = request.get_data() return_j = generator.add_enforced_connection(j); print "got return j" resp = make_response(return_j, 200) resp.headers['Content-Type'] = "application/json" resp.headers['Access-Control-Allow-Origin'] = "*" return resp @app.route('/change_glob_options', methods=['POST']) def change_glob_options(): print("enforcing a new connection") j = request.get_data() return_j = generator.change_glob_options(j); print "got return j" resp = make_response(return_j, 200) resp.headers['Content-Type'] = "application/json" resp.headers['Access-Control-Allow-Origin'] = "*" return resp if __name__ == '__main__': app.run(debug=False)
print(filename) photos.save(filename[0], name=name + '.') name = str("stylized") photos.save(filename[1], name=name + '.') success = True return redirect(url_for('running_process')) else: success = False return render_template('index.html', form=form, success=success) @app.route('/upload_complete', methods=["POST", "GET"]) def running_process(): return uploaded() @app.route('/show_image', methods=["GET", "POST"]) def show_result(): image_file = url_for('static', filename="output/output.png") return render_template('image_complete.html', image_file=image_file) @app.teardown_request def job_done(exception): return exception if __name__ == '__main__': app.config['SERVER_NAME'] = "0.0.0.0:9000" app.run(debug=True, host='0.0.0.0', port=9000)
# Create all database tables. db.create_all() # Return app. return app if __name__ == '__main__': # Create app. app = create_app() # Create database tables. db.create_all() # Create default super admin user in database. create_super_admin() # Create default admin user in database. create_admin_user() # Create default test user in database. create_test_user() # Generate routes. generate_routes(app) # Run app. app.run(port=5000, debug=True, host='localhost', use_reloader=True)
now = datetime.datetime.now() end = now.strftime(DATE_FORMAT) start_buf = now + datetime.timedelta(minutes=-120) start = start_buf.strftime(DATE_FORMAT) command = "returnChartData" period = "300" dic1 = get_data(command, "USDT_XRP", start, end, period) dic2 = get_data(command, "USDT_BTC", start, end, period) index = 0 for i in dic1: converted_ticks = now + datetime.timedelta(microseconds=i['date'] / 10) dic1[index]['date'] = converted_ticks.strftime("%d:%H:%M:%S") index = index + 1 index = 0 # print "dic1: "+str(dic1) # print "dic2: "+str(dic2) for j in dic2: converted_ticks = now + datetime.timedelta(microseconds=j['date'] / 10) dic2[index]['date'] = converted_ticks.strftime("%d:%H:%M:%S") index = index + 1 return render_template('view.html', menu=menus, text1=dic1, text2=dic2) # main if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=5012, threaded=True)
player.pause() return "PAUSED" @app.route("/resume") def resume_playing(): global player player.resume() return "RESUMED" @app.route('/play/<song>/') def play_test_song(song=None): global stop_event global player if(player is not None): player.pause() filename = os.path.join(UPLOAD_FOLDER, '{}.wav'.format(song)) player = AudioParser(filename) player.begin() import time # time.sleep(2) # e.set() # time.sleep(2) # e.clear() return "End" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
def webservice(): app.run(host=server_opts['listen_ip'], port=server_opts['listen_port'], threaded=True)
data.pop(1) return json.dumps([{'success': True, 'message': "Success",'data': tuple(data)}]) return json.dumps([{'success': False, 'message': "User not signed in"}]) @app.route("/get_user_messages_by_token",methods=["GET"]) def get_user_messages_by_token(): token=request.args.get("token") if request.method == 'GET': if dh.is_user(dh.get_email_by_token(token))==False: return json.dumps([{'success': False, 'message': "No such user"}]) return json.dumps([{'success': True, 'message': "Success",'data':dh.messages_by_token(token)}]) @app.route("/post_message",methods=["POST"]) def post_message(): email=request.args.get("email") token=request.args.get("token") mess =request.args.get("message") if request.method == 'POST': if dh.is_user_logged_in_token(token)==False: return json.dumps([{'success': False, 'message': "Not signed in"}]) if dh.is_user(email)==False: return json.dumps([{'success': False, 'message': "Illegal recipient"}]) return json.dumps([{'success': dh.post_msg(dh.get_email_by_token(token),email,mess),'message':"message sent"}]) if __name__ == '__main__': #database_helper.init_db(app) app.debug = True app.run()
# Get prediction results to display the bar chart @app.route("/getMLBarChart/<textData>") def getMLBarChart(textData): pred = vect.transform([textData]) prob = nb.predict_proba(pred) dct = {} for (x, y), value in numpy.ndenumerate(prob): wine = list(le.inverse_transform([y])) dct[wine[0]] = str("{:.2f}".format(value * 100)) dfBarChart = pd.DataFrame({ "wine": list(dct.keys()), "probability": list(dct.values()) }).sort_values(by=['probability'], ascending=False).head(5) json = dfBarChart.to_json(orient='records', date_format='iso') response = Response(response=json, status=200, mimetype="application/json") return response @app.route("/") def main(): return render_template("index.html") if __name__ == "__main__": app.run(host='127.0.0.1', port=8004)
#defect = sub_chapter['defects'][d] #defect['status'] = form['status'] #defect['url'] = form['url'] #defect['tags'] = [tag.strip() for tag in form['tags'].split(',')] #defect['description'] = form['description'] #defect['follow-up'] = form['follow-up'] #print '------here------' #r.hset(DB_NAME, 'chapters', dumps(chapters)) #r.save() #return render_template('index.html') #@app.route('/delete/<int:chapter>/<int:sub_chapter>/<int:defect>') #def delete(chapter, sub_chapter, defect): #f = open(DB_FILE, 'w+b') #data = loads(f.read()) #sub_chapter = data['chapters'][chapter]['sub-chapters'][sub_chapter] #del(sub_chapter['defects'][defect]) #if len(sub_chapter['defect']) == 0: #del(data['chapters'][chapter]['sub-chapters']) #f.close() if __name__ == '__main__': app.run(debug=DEBUG)
if session.get('session_token') != None: return render_template('profile.html') else: return render_template('login.html') @app.route('/Select_Interests') def Select_Interests(): if session.get('session_token') != None: return render_template('Settings.html') else: return render_template('login.html') @app.route('/share/<path:path>') def share(path): SinglePost = getPost.getSinglePost(path) return render_template('Posts.html',SinglePost=SinglePost) @app.route('/Settings') def Settings(): return render_template('Settings.html') port = int(os.environ.get('PORT', 5000)) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.run(host="0.0.0.0",debug=True,port=port) # font images) #font images
return "randomized" @app.route('/processState', methods=["POST"]) @cross_origin() def process_state(): main.network.processState() return "processed" # Accepting file uploads to the server @app.route('/upload', methods=["POST"]) @cross_origin() def do_upload(): uploads = request.files.get('uploads[]') # name, ext = os.path.splitext(upload.filename) # if ext not in ('.png','.jpg','.jpeg'): # return 'File extension not allowed.' save_path = 'uploads/' for upload in uploads: upload.save(save_path, overwrite=True) # Appends upload.filename automatically return index() @app.route('/data', methods=["GET"]) @cross_origin() def get_data(): return main.network.data() app.run(host='0.0.0.0', port=8080, debug=DEBUG)
def video_feed(): return Response(generate()) if __name__ == '__main__': # construct the argument parser and parse command line arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--ip", type=str, required=True, help="ip address of the device") ap.add_argument("-o", "--port", type=int, required=True, help="ephemeral port number of the server (1024 to 65535)") ap.add_argument("-f", "--frame-count", type=int, default=32, help="# of frames used to construct the background model") args = vars(ap.parse_args()) t = threading.Thread(target=live_stream_recognition, args=(args["frame_count"], )) t.daemon = True t.start() app.run(host=args["ip"], port=args["port"], debug=True, use_reloader=False)
data={} data['success']=True data['messages']=messages return json.dumps(data) else: data = {} data['success'] = False data['message'] = 'Unsuccessful' json_token = json.dumps(data) return json_token @app.route('/postmessage/',methods=['POST']) def post_message(): if request.method=='POST': token=request.form.get('token') wall=request.form.get('wall') message=request.form.get('message') print(token,wall,message) posted=database_helper.postmessage(token,wall,message) return posted def init_db(): with closing(database_helper.connect_db()) as db: with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() if __name__ == '__main__': app.run(Debug=True)
saida = atualiza_regra(request.json["user"],request.remote_addr,regra_validada["regra"]) return saida else: return regra_validada else: return JSONEncoder().encode({"Error":"No permission for the user %s"})%(request.json["user"]) else: return "Failed to authenticate the user %s"%(request.json["user"]) @app.route('/tzion', methods = ['DELETE']) def apaga_regra(): authentication = autenticacao(request.json["user"],request.json["password"],request.remote_addr) if authentication == "200 OK": grupo_auth = grupo(request.json["user"],request.json["password"],request.remote_addr) if grupo_auth == "200 OK": regra_validada = fix_json(request.json["regra"]) if type(regra_validada) is dict: saida = remove_regra(request.json["user"],request.remote_addr,regra_validada["regra"]) return saida else: return regra_validada else: return JSONEncoder().encode({"Error":"No permission for the user %s"})%(request.json["user"]) else: return "Failed to authenticate the user %s"%(request.json["user"]) if __name__ == '__main__': porta = int(os.getenv('PORT', 8080)) print 'Starting server on port:{0}'.format(porta) app.run(host='0.0.0.0', port=porta, debug=True)
def delete_model(model, the_id): if not session.get('logged_in'): return redirect(url_for('register')) if model == 'dest': tablename = "destinations" redir = "" elif model == 'visit': tablename = "visits" g.cursor.execute("SELECT day FROM visits WHERE id = %s", the_id) redir = "#%s" % g.cursor.fetchone()['day'] else: abort(404, "invalid model") g.cursor.execute("DELETE FROM %s WHERE id = %%s" % tablename, the_id) g.cursor.execute("DELETE FROM miles WHERE miles = 0") #i don't remember why this is in here return redirect(url_for('calendar') + redir) @app.after_request def close_db(response): g.cursor.close() g.db.commit() g.db.close() return response ########################################################### if __name__ == '__main__': CONFIG = json.load(open("%s/config.json" % APP_ROOT)) app.run(host='0.0.0.0', port=5053)
print(chars) print(labelr) print(labelc) print(colors) plt.table(cellText=chars, rowLabels=labelr, colLabels=labelc, rowColours=[(1, 1, 1)] * len(df.index), colColours=[(0.5, 0.5, 1)] * 3, cellColours=colors, cellLoc='center', loc='upper left') print("ccc") price = 0 for i in range(len(df.index)): price = price + float(df.iloc[i][2]) p_price = "{:,}".format(price) plt.text(0.005, 0.05, 'Estimated Total price is ' + p_price + ' Bath.', fontsize=15) plt.axis('off') plt.savefig('res/' + ivaa_case + '.png') print("zzzz") return send_file('res/' + ivaa_case + '.png', mimetype='image/jpg') if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
#coding:utf8 #file is used to import hashlib import os from flask import app,request,Flask, make_response app = Flask(__name__) __author__ = 'tanghan' TOKEN = 'weixin' @app.route('/weixin',methods=['POST','GET']) def wechat_auth(): if request.method=='GET': token = TOKEN data = request.args signature = data.get('signature') timestamp = data.get('timestamp') nonce = data.get('nonce') echostr = data.get('echostr') s = [timestamp, nonce, token] s.sort() s = ''.join(s) if (hashlib.sha1(s).hexdigest() == signature): return make_response(echostr) if __name__ == "__main__": app.run(debug=True, port=80, host='0.0.0.0')
for comment in Comment.query.filter_by(page_name=pageName).all()]) @app.route("/comments/<pageName>", methods=['POST']) def AddComments(pageName): print(pageName) cm = request.get_json() print(cm) newComment = Comment(page_name=pageName, author=cm['author'], content=cm['content'], email=cm['email'], comment_time=str(datetime.now())) db.session.add(newComment) return DbCommit() @app.route("/comments/<commentId>", methods=['DELETE']) def DeleteComments(commentId): comment = Comment.query.filter_by(id=commentId).first() if not comment: return 'No record', 404 comment.deleted = True return DbCommit() @app.route("/recover/comments/<commentId>", methods=['POST']) def RecoverComment(commentId): comment = Comment.query.filter_by(id=commentId).first() if not comment: return 'No record', 404 comment.deleted = 0 return DbCommit() if __name__ == '__main__': app.run(host='0.0.0.0', port=8088, debug=True)
app.config.update( DEBUG=True ) # Returns the BTC balance of the current user def get_balance(): return "-" # Sends payment from address # Address must be associated with account @app.route('/send') def send(): return "send" # Generates an address # Shows receive history # Associates address with account @app.route('/receive') def receive(): return "rec" @app.route('/transactions') def transactions(): return "txn" @app.route('/') def home(): return "YOURE ON THE HOMEPAGE. KINNARD IS A F****R" if __name__ == '__main__': app.run(host='127.0.0.1')
followup = "I sense some negativity. Let me try to divert your mind. Tell me something about your favourite books or movies." elif mood[0] == 'neutral' or mood[0] == 'negative': followup = "I'm so sorry to hear that. I can understand your situation. Feel free to rant to me. I'm always here to listen." rant = True elif scores['pos'] > .3: followup = "I love this positivity!! Let's keep this up for tomorrow by making some plans or goals you wish to accomplish." elif scores['neu'] > .3: if mood[0] == 'positive' or mood[0] == 'neutral': followup = "Hmm... I see. Thank you for sharing that with me. Yeah, I'm sensing very neutral vibes. But let's use this as inspiration to have a better day tomorrow by coming up with some goals!" elif mood[0] == 'negative': followup = "I'm sorry that today was pretty meh. I'm always here for you. If you need to get something off your chest, then, please, go ahead." rant = True return followup, rant def send_mail(plan, EMAIL): message = MIMEMultipart() message["From"] = EMAIL message["To"] = EMAIL message["Subject"] = "AI_BOT" message.attach(MIMEText(plan, "plain")) text = message.as_string() context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login("*****@*****.**", os.environ['EMAIL_PASSWORD']) server.sendmail("*****@*****.**", EMAIL, text) app.run(port=5000, debug=True)
return render_template('home.html', current_time=now.ctime(), isAuthenticated = user_is_authenticated()) @app.route('/initdb', methods=['GET']) def init(): make_structure() return "Success" @app.route('/leagues') def leagues_page(): return render_template('leagues.html', isAuthenticated = user_is_authenticated()) if __name__ == '__main__': VCAP_APP_PORT = os.getenv('VCAP_APP_PORT') if VCAP_APP_PORT is not None: port, debug = int(VCAP_APP_PORT), False else: port, debug = 5000, True VCAP_SERVICES = os.getenv('VCAP_SERVICES') if VCAP_SERVICES is not None: app.config['dsn'] = get_elephantsql_dsn(VCAP_SERVICES) else: app.config['dsn'] = """user='******' password='******' host='localhost' port=54321 dbname='itucsdb'""" CurrentConfig.appconfig = app.config['dsn'] app.run(host='0.0.0.0', port=port, debug=debug)
from flask import app, Flask, render_template, request, safe_join, send_from_directory app = Flask(__name__) @app.route("/") def control_blinds(): return render_template("bootstrap_test.php") #@app.route('/<any(css, img, js):folder>/<path:filename>') #def toplevel_static(folder, filename): # filename = safe_join(folder, filename) # cache_timeout = app.get_send_file_max_age(filename) # return send_from_directory(app.static_folder, filename, cache_timeout=cache_timeout) if __name__ == '__main__': app.run(host="0.0.0.0", debug=True)
#help(reactor) thread_object = threading.Thread(group=None, target = get, name=None, args=(key,event), kwargs={}) thread_object.start() #data = reactor.callInThread(get,[key,event],{})#reactCaget(key,event) #data = get(key,event) #cprint("The data is %s" % str(data)) #time.sleep(1); #print "printing from server %s" % data.callback() #f() #help(event) #cprint("got to wait") #cprint("The value of event.wait is " + str(event.isSet())) #event.set() if event.wait(): #cprint("Result returned") cprint("global result = %s" % global_result) cprint(str(type(global_result))) if (len(global_result) > 0): return global_result[0]; else: return(str(global_result)); else: cprint("Fail... Time out") #cprint("got through wait") return "Time-out occured" if __name__ == "__main__": app.debug = True app.run();
app.py static -- js -- -- script.js -- css -- -- style.css -- img -- -- icon.png templates -- index.html ''' @web.register("/js/<path:path>") def load_js(path): return send_from_directory("static/js", path) @web.register("/css/<path:path>") def load_css(path): return send_from_directory("static/css", path) @web.register("/img/<path:path>") def load_img(path): return send_from_directory("static/img", path) if __name__ == "__main__": app.run(host='0.0.0.0', port=1337)
return jsonify(return_message, return_status) @app.errorhandler(403) def page_not_found(e): return render_template('/views/403.html'), 403 @app.errorhandler(404) def page_not_found(e): return render_template('/views/404.html'), 404 @app.errorhandler(500) def page_not_found(e): return render_template('/views/500.html'), 500 # Check if the executed file is the main program and run the app if __name__ == "__main__": # Setup logging for our application logging.basicConfig(filename='my_tableau_extensions.log', format='%(levelname)s %(message)s', filemode='w') logger = logging.getLogger() logger.setLevel(logging.INFO) # Run the app on the localhost with the specified port app.run(host='0.0.0.0', port=5013)
request.form['date'], request.form['description'], request.form['keywords']) return simplejson.dumps({'message': 'OK'}) return simplejson.dumps({'message': 'Inadequate permissions'}) @app.route("/register", methods=["POST"]) def register(): username = request.form['username'] password = request.form['password'] if len(password) < 8: return simplejson.dumps( {'message': 'Your password must be at least 8 characters long!'}) uid = db.add_user(g.db, username, password) if uid: login_user(User(uid)) return simplejson.dumps({'message': 'OK'}) return simplejson.dumps({'message': 'Username already exists!'}) # callback to relaad the user object @login_manager.user_loader def load_user(userid): return User(userid) if __name__ == "__main__": app.debug = True app.secret_key = "the cake is a lie, and I don't trust the pie either." app.run()
morph = Kkma.pos(okja) # count = count + 1 # print(count, "번째 문장 분석결과 : ", morph) # print("\n") # f.writelines(str(morph)) # f.writelines("\n") return morph # f.close()r @app.route("/cosmos/KStars/morpList/KoNLPy", methods=['POST']) def cosmos_morp_konlpy_board(): data = request.json for i in range(len(data)): analysis = KKma(data[i]['text']) resultList = analysis.showmorp() data[i]['analysisResult'] = resultList for i in range(len(data)): print(data[i]['analysisResult']) return jsonify(data) adadadsdad = "adsaddsadadsadad" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
from flask import app, request, Flask, render_template, request, url_for import serial import os ser = serial.Serial("/dev/ttyACM0", 9600) tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'template') app = Flask(__name__, template_folder=tmpl_dir) app.config.from_object(__name__) @app.route("/",methods=["GET","POST"]) def index(): return render_template("index.html") @app.route("/cadastro", methods=["GET","POST"]) def cadastro(): if request.method == "POST": dado = request.form["msg"] for char in str(dado): ser.write(char) return render_template('cadastro.html') if __name__ == '__main__': app.run(host='0.0.0.0') #para rodar nao localmente #app.debug = True #app.run()
from flask import Flask, app app = Flask(__name__) @app.route('/helloworld') def Helloworld(): return '<h1>Hello world Welcome to Heroku !!!</h1>' if __name__ == '__main__': app.debug = True app.run(host = '0.0.0.0', port = 8080)
# global variable = 100500 @app.route('/download/<filename>', methods=['GET', 'POST']) def download(filename): uploads = os.path.join(app.root_path, "files") print('*** uploads = ', uploads) return send_from_directory(directory=uploads, filename=filename) @app.route("/downloadfile/<filename>") def downloadfile(filename=None): if filename is None: self.Error(400) try: rt_path = current_app.root_path return send_file(rt_path + "/files/" + filename, as_attachment=True) except Exception as e: self.log.exception(e) self.Error(400) if __name__ == '__main__': print(colored('*** STARTING SERVER ***', 'green')) #global variable variable = 100500 print(colored('*** VARIABLE = ', 'green'), variable) app.run(debug=True, host='0.0.0.0')
else: response_dict[ item] = transformer.extract_relevant_portion_from_mask( image, detections) return jsonify(response_dict), 201 # TODO(amank): Find a way to deal with masks, will mostly depend upon the kind the problem we have at hand @app.route(config_file.DEFAULT_API_NAME, methods=['POST']) def get_detections(): #print('inside api') if not request.json or not 'image' in request.json: abort(400) #print('Inside approute aadhar documetn extraction') image = base64_to_skimage(request.json['image']) #print(image.shape()) items_of_interest = None if 'item_of_interest' in request.json: items_of_interest = request.json['item_of_interest'] #print('items of interest') detections = model.detect([image])[0] # NOTE: detections contains masks, scores, rois and class_id. # Out of these it is cost-effecient to send the scores, rois, class_id over the network # But in case you wish to use the mask, find a more efficient way to deal with it. # It is humungous and will take forever to transmit over a network return get_item_of_interest(detections, items_of_interest, image) if __name__ == '__main__': app.run(host="0.0.0.0", port=8080, debug=True)
import flask from flask import app, render_template app = app.Flask(__name__) @app.route('/') def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug=True)
title_list.append(title) echo_id_list.append(echo_id) artist_list_pos.append(artist_name) df_artist = DataFrame({'genre': genre_name_list, 'weight': genre_weight_list, 'freq': genre_freq_list, 'echo_id': echo_id_list, 'title': title_list, 'artist': artist_list_pos, 'perf':perf_list}) df_artist['wf'] = df_artist.weight * df_artist.freq df_artist.sort('wf', ascending = False) if len(df_artist) > 5: return 1, df_artist else: return 0,0 else: return 0,0 if __name__ == '__main__': '''Set debug to False if running on AWS ''' port = int(os.environ.get('PORT', 8080)) app.debug = False app.run(host='0.0.0.0', port=port)