class BaseHTTPService(BaseService): template_folder = None application_name = None def setup_server(self): super(BaseHTTPService, self).setup_server() # Create an Flask application for this service using the service name self.app = Flask(self.application_name or self.__class__.__name__, template_folder=self.template_folder or None) methods = dir(self) # Attach each route in the class for name in [x for x in methods if x.startswith("route_")]: method = getattr(self, name) self.app.add_url_rule(method.rule, name, method) self.logger.debug("Adding handler '%s' for '%s' rule", name, method.rule) # Attach error handlers in the class for name in [x for x in methods if x.startswith("error_")]: method = getattr(self, name) code = int(name.split("_", 2)[1]) self.app.error_handler_spec[None][code] = method self.logger.debug("Adding handler '%s' for error code '%d'", name, code) def run(self): self.logger.debug("Waiting for clients") try: self.app.run(self.listener_address, self.listener_port) except KeyboardInterrupt: self.logger.warning("Canceled by the user") self.stop() def stop(self): self.logger.debug("Stopping server")
def run(): # TODO (wajdi) Make configurable passed parameter port = 9131 app = Flask('fake_ubersmith') data_store = DataStore() base_uber_api = UbersmithBase(data_store) AdministrativeLocal().hook_to(app) Uber(data_store).hook_to(base_uber_api) Order(data_store).hook_to(base_uber_api) Client(data_store).hook_to(base_uber_api) base_uber_api.hook_to(app) _get_logger(app) app.run(host="0.0.0.0", port=port)
def main(): ''' This method registers all the end points of the application ''' app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False api = Api(app) @app.before_first_request def create_tables(): db.create_all() api.add_resource(UserHandler, '/api/user', '/api/user/<string:name>') api.add_resource(AddressHandler, '/api/address', '/api/address/<string:id>') api.add_resource(CourseHandler, '/api/course', '/api/course/<string:name>') api.add_resource(StudentHandler, '/api/student', '/api/student/<string:id>') from database.config import db db.init_app(app) app.run(debug=False)
from flask import flash, render_template, request from flask.app import Flask app = Flask(__name__) @app.route('/') def home(): return render_template("index.html") @app.route("/", methods=['POST']) def receive_data(): name = request.form["username"] password = request.form['password'] return f"<h1>Name: {name}, Password: {password}</h1>" if __name__ == "__main__": app.run(debug=True)
db.app = app db.init_app(app) Log.information(__name__, "Setting up cache...") cache.init_app(app, config={ "CACHE_TYPE": Configuration["cache_type"], "CACHE_DIR": Configuration["cache_path"] }) Log.information(__name__, "Setting up mailservice...") mailservice.init_app(Configuration["email_host"], Configuration["email_host"], Configuration["email_user"], Configuration["email_pass"]) # Register blueprints # ---------------------------------------------------------------------------- # Log.information(__name__, "Registering blueprints...") app.register_blueprint(BlueprintCore) package = blueprints path = blueprints.__path__ prefix = blueprints.__name__ + "." for module_loader, name, ispkg in pkgutil.walk_packages(path, prefix): module = importlib.import_module(name) if not hasattr(module, "blueprint"): continue Log.information(__name__, "Importing blueprint %s" % (name)) app.register_blueprint(module.blueprint) # Run application # ---------------------------------------------------------------------------- # app.run(host="0.0.0.0", port=5000)
# coding=utf-8 from flask.app import Flask from api.core.views import alter_response from resources import (auth_blueprint, user_blueprint, process_blueprint, ticket_blueprint) app = Flask(__name__) @app.route('/') def home(): return 'Kanban API v1' app.register_blueprint(auth_blueprint, url_prefix='/api') app.register_blueprint(user_blueprint, url_prefix='/api') app.register_blueprint(process_blueprint, url_prefix='/api') app.register_blueprint(ticket_blueprint, url_prefix='/api') app.after_request(alter_response) if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True)
# self.logger.info("BODY : " + str(self.body)) self.logger.info("===============================================") # [RESTIF->WEB] SEND RESPONSE name = content['name'] age = content['age'] return jsonify(name=name, age=age) # overide method def setComplete(self, rspCode, reqId, rcvMsg): self.msg = rcvMsg self.rspCode = rspCode self.receiveReqId = reqId # overide method def setResMessage(self, data): resMsg = HttpRes() return resMsg if __name__ == '__main__': app = Flask(__name__) api = Api(app) api.add_resource(ttt, '/ns_descriptors') app.run(threaded=True, host='0.0.0.0')
from analyzer import analysis_commits, analysis_category, get_datetime_from_string from api import AnalyzerApi app = Flask(__name__) @app.route('/') def analyzer_run() -> str: # Parse args repo = request.args.get('repo') branch = request.args.get('branch', default='master') since = get_datetime_from_string(request.args.get('since', default=datetime.min)) until = get_datetime_from_string(request.args.get('until', default=datetime.max)) repo_urls = AnalyzerApi(repo) # Top author top_authors = analysis_commits(repo_urls.get_commits(sha=branch, since=since, until=until)) # Issues issues = analysis_category(repo_urls, category='issues', since=since, until=until, within=timedelta(days=14) ) # Pull requests pulls = analysis_category(repo_urls, category='pulls', since=since, until=until, within=timedelta(days=30) ) # Return return f'Top authors repos:\n{top_authors}\n{issues}\n{pulls}' if __name__ == "__main__": app.run(host='0.0.0.0', port=os.getenv('PORT')) # port 5000 is the default
''' Created on Jan 9, 2018 @author: shrikant_jagtap ''' from flask.app import Flask from flask.templating import render_template app = Flask(__name__) @app.route("/") @app.route("/index") def get_hello(): user = {"username": "******"} return render_template('index.html', title='Home', user=user) if __name__ == '__main__': app.run('ip_address')
from flask import json, request from flask.app import Flask logging.basicConfig(filename='leboncoin.log', level=logging.DEBUG) app = Flask(__name__) app.json_encoder = CustomJSONEncoder def providers(): return [LeBonCoinProvider()] @app.route('/api') def list(): page = request.args.get('page', 1) location = request.args.get('location', None) provider = LeBonCoinProvider() return app.response_class(json.dumps({ 'count': provider.count(location), 'houses': provider.list(page=page, location=location) }), mimetype='application/json') if __name__ == '__main__': app.run(host="0.0.0.0", port=8888, debug=True)
.filter(file_details.name == filename)\ for y in get_id: current_id = y.id file_specs.query\ .filter(file_specs.file_details_id == current_id)\ .delete() file_details.query\ .filter(file_details.name == filename)\ .delete() path = os.path.join('./files', filename) shutil.rmtree(path) db.session.commit() flash("Twój plik został pomyślnie usunięty", "info") return redirect('/') except: db.session.rollback() flash( "Niestety nie udało się usunąć pliku błąd! Prawdopodobnie plik który próbujesz usunąć już nie istnieje", "danger") return redirect('/summary') if __name__ == "__main__": db.create_all() app.run(debug=True, port=1234)
p.bloodtype) return redirect("/web/patients") @app.route("/web/patient/delete/<int:patient_id>", methods=['GET']) def remove_web_patient(patient_id): p = Patient.query.filter_by(patient_id=patient_id).first() db.session.delete(p) db.session.commit() return redirect("/web/patients") @app.route("/web/report/delete/<int:report_id>", methods=['GET']) def remove_web_report(report_id): r = Report.query.filter_by(report_id=report_id).first() db.session.delete(r) db.session.commit() return redirect("/web/reports") if __name__ == '__main__': db.create_all() #example_Report() #example_Patient() #db.create_all() app.run(port=5500) pass
nat_dt = dt.replace(tzinfo=None) to_fmt = '%d-%m-%Y@%I:%M:%S %p' return nat_dt.strftime(to_fmt) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", type=bool, nargs='?', const=True, default=False, dest="debug", help="Run the server in debug mode.") parser.add_argument("cfg_file_path", type=str, help="Scrapper runner config file path.") args = parser.parse_args() app.secret_key = V.random_str(size=30) V._init_db() with open(args.cfg_file_path, "r") as cfg_file: V.CONFIG = json.load(cfg_file) logging.info("CONFIG: " + str(V.CONFIG)) app.run(host=V.CONFIG["host"], port=V.CONFIG["port"], threaded=True, debug=args.debug)
''' Created on Mar 25, 2019 @author: Stan Fedetsov ''' from flask.app import Flask HTTP_PORT = 8080 app = Flask(__name__) @app.route("/") def main(): return "<h3>Stan Fedetsov. Configuration Project.</h3><p>This is a test!!!</p>" if __name__ == '__main__': app.run(host="0.0.0.0", port=HTTP_PORT)
for node in nodes: blockchain.register_node(node) response = { 'message': 'New nodes have been added', 'total_nodes': list(blockchain.nodes), } return jsonify(response), 201 @app.route('/nodes/resolve', methods=['GET']) def consensus(): replaced = blockchain.resolve_conflicts() if replaced: response = { 'message': 'Our chain was replaced', 'new_chain': blockchain.chain } else: response = { 'message': 'Our chain is authoritative', 'chain': blockchain.chain } return jsonify(response), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
for header_prefix in PROXY_RESPONSE_HEADER_PREFIXES: if header.lower().startswith(header_prefix): # copy header response.headers[header] = url_response.headers[header] break return response if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", help="debug mode, pause on exception", action="store_true") parser.add_argument("-b", "--bind", help="bind address", default="0.0.0.0") parser.add_argument("-p", "--port", help="server port", default=8005, type=int) parser.add_argument("-i", "--inject", help="inject script", default=None) args = parser.parse_args() if args.inject: with open(args.inject) as f: PROXY_INJECT_SCRIPT = f.read() app.run(host=args.bind, port=args.port, debug=args.debug)
from flask.templating import render_template from flask.globals import request app=Flask(__name__) @app.route("/") def function(): if request.method=="GET": return render_template("homepage.html") @app.route("/sugestion/<suggest>",methods=["GET","POST"]) def suggestion(suggest): suggestions='' states=["Andhra Pradesh","Arunachal Pradesh ","Assam","Bihar","Chhattisgarh","Goa","Gujarat","Haryana","Himachal Pradesh","Jammu and Kashmir","Jharkhand","Karnataka","Kerala","Madhya Pradesh","Maharashtra","Manipur","Meghalaya","Mizoram","Nagaland","Odisha","Punjab","Rajasthan","Sikkim","Tamil Nadu","Telangana","Tripura","Uttar Pradesh","Uttarakhand","West Bengal","Andaman and Nicobar Islands","Chandigarh","Dadra and Nagar Haveli","Daman and Diu","Lakshadweep","National Capital Territory of Delhi","Puducherry"] if suggest is not None: for i in range(len(states)): if states[i].upper().startswith(suggest.upper()): suggestions +=states[i]+"<br>" print(suggestions) return f"{suggestions}" if __name__ == "__main__": app.run(host="localhost",port=1418,debug=True)
doctor2 = DoctorModel(2, 4, None, '12345ASDFG', None, None, None) doctors = [doctor1, doctor2] for obj_doctor in doctors: obj_doctor.save_to_db() pass pass # Patient if PatientModel.query.first() is None: patient1 = PatientModel(3, 1, 20, 'O+', 60.00, 'Male', 1.84, None, None, None) patient2 = PatientModel(4, 2, 26, 'AB+', 72.00, 'Female', 1.95, None, None, None) patients = [patient1, patient2] for obj_patient in patients: obj_patient.save_to_db() pass pass pass # It help to create tables before first request @app.before_first_request def create_tables(): db.create_all(app=app) load_tables() app.run(debug=app_config['env'].DEBUG)
# -*- coding: utf-8 -*- ''' Created on 2015年10月12日 @author: leilei ''' from flask.app import Flask app = Flask(__name__) @app.route('/<s>') app.run(host="127.0.0.1", port=80, debug=True)
from flask.app import Flask from flask_cors import CORS from blog.models.exts import db from blog.models.exts import bcrypt from blog.models.modetool import creat_db from blog.urls.main import init_url config = 'conf.flask.config.ProductionConfig' #config = 'conf.flask.config.DevelopmentConfig' app = Flask(__name__, static_folder="./web/static", template_folder="./web") CORS(app) app.config.from_object(config) db.init_app(app) bcrypt.init_app(app) with app.app_context(): creat_db() init_url(app) if __name__ == '__main__': app.run(port=8000)
query = """ SELECT * FROM `bangkitproject-314115.Childpedia.user` WHERE id = @user_id """ job_config = bigquery.QueryJobConfig(query_parameters=[ bigquery.ScalarQueryParameter("user_id", "STRING", id) ]) queryJob = client.query(query, job_config=job_config) records = [dict(row) for row in queryJob] jsonObject = json.dumps(str(records)) length = len(records) # if encyclopedia id does not match if length == 0: message = jsonify({ 'error': 'user_not_found', 'message': 'User is not found' }) return make_response(message, 404) return jsonObject if __name__ == '__main__': app.run(host='0.0.0.0', port=10533)
visitor_ratings = app_controller.get_all_visitor_ratings(movie_id) movie_info = app_controller.get_movie_info(movie_id) return render_template('all_movie_ratings.html', system_user_ratings=system_user_ratings, visitor_ratings=visitor_ratings, movie_info=movie_info) @app.route('/showUserInfo') def show_user_info(): user_id = request.args.get('userId') is_system_user = request.args.get('systemUser') session_id = request.args.get('sessionId') user_ratings = [] if session_id: user_ratings = app_controller.get_all_ratings_for_session(session_id.encode('utf-8')) else: user_ratings = app_controller.get_all_ratings_for_user(user_id.encode('utf-8'), is_system_user.encode('utf-8')) user_info = {'user_id':user_id, 'session_id':session_id} return render_template('user_info.html', user_ratings=user_ratings, user_info=user_info) @app.route('/compareRecommendationAlgos') def compare_recommendation_algos(): recommendations, user_id, nimfa_rmse, scikit_rmse = app_controller.get_recommendations_for_system_user(); return render_template('compare_recommendation_algos.html', recommendations=recommendations, user_id=user_id, nimfa_rmse=nimfa_rmse, scikit_rmse=scikit_rmse) def ok_response(): return json.dumps({'success':True}), 200, {'ContentType':'application/json'} if __name__ == '__main__': app.run("0.0.0.0", 9090, debug=True)
import subprocess subprocess.call(['rm', '/home/rrangkuti/web/bayarkan/memory']) from common import logger_factory from flask.app import Flask from controllers import home_controller import os logger = logger_factory.create_logger(__name__) logger.info('starting up...') main = Flask(__name__) main.secret_key = os.urandom(24) main.register_blueprint(home_controller.home_router, url_prefix='/') if __name__ == '__main__': main.run(port=29000)
elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_user_id(request.form['username']) is not None: error = 'The username is alredy taken' else: g.db.execute('''insert into user (username, email, pw_hash) values (?, ?, ?)''', [request.form['username'], request.form['email'], generate_password_hash(request.form['password'])]) g.db.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('register.html', error=error) @app.route('/logout') def logout(): ''' Logs the user out. :return: ''' flash('You were logged out') session.pop('user_id', None) return redirect(url_for('public_timeline')) # add some filters to jinja app.jinja_env.filters['datetimeformat'] = format_datetime app.jinja_env.filters['gravatar'] = gravatar_url if __name__ == '__main__': init_db() app.run()
query_response=query_response) @app.route("/genre_byid/<int:id>", methods=["DELETE"]) def delete_genre_by_id(id): if request.method == "DELETE": query_response = session.query(AnimeByGenre).filter( AnimeByGenre.id == id).delete() session.commit() return "this is working" else: return "Error: something gone wrong." # @app.route("/anime_busqueda<string:busqueda>", methods = ['GET']) # def search_by_id(busqeda): # conn = conn_db # query = "SELECT * FROM animebysearch WHERE title = {busqueda}" # return render_template("anime_busqueda.html") # @app.route("/asdsa", methods = ['GET', 'POST']) # def testep(): # return render_template("anime_search.html") # @app.route("/agregar", methods = ['GET', 'POST']) # def ajustar(): # return render_template("anime_search.html") if __name__ == "__main__": app.run(debug=True, port=5000) #print(var)
return "Serviços de OCR de imagens." def main(): OCRUtils.application = ABOCRServicesAPP #api resource routing _api.add_resource(ABOCRServices, '/ocr/getProcessedImg', '/ocr/getProcessedImg/<path:imgPath>', '/ocr/processImage') vparInit() result = Vpar.ocrReadImg('/tmp/B0064GK.BMP') print(result.strResult) #Se este arquivo é executado, roda o servidor do Flask. Para rodar no Gunicorn, basta #iniciar o arquivo correspondente com o ABServicesAPP.run executando no contexto do Gunicorn. if __name__ == "__main__": main() ABOCRServicesAPP.config.from_object(DevConfig) OCRUtils.setup_logging("Flask") # Host e porta do servidor SERVER_HOST = '0.0.0.0' SERVER_PORT = ABOCRServicesAPP.config.get("SERVER_PORT") DEBUG = ABOCRServicesAPP.config.get("APP_LOG_LEVEL") == logging.DEBUG ABOCRServicesAPP.run(debug=DEBUG, threaded=True, host=SERVER_HOST, port=SERVER_PORT)
import logging from api.CustomJSONEncoder import CustomJSONEncoder from api.providers.leboncoin import LeBonCoinProvider from flask import json, request from flask.app import Flask logging.basicConfig(filename='leboncoin.log', level=logging.DEBUG) app = Flask(__name__) app.json_encoder = CustomJSONEncoder def providers(): return [ LeBonCoinProvider() ] @app.route('/api') def list(): page = request.args.get('page', 1) location = request.args.get('location', None) provider = LeBonCoinProvider() return app.response_class(json.dumps({ 'count': provider.count(location), 'houses': provider.list(page=page, location=location) }), mimetype='application/json') if __name__ == '__main__': app.run(host="0.0.0.0", port=8888, debug=True)
"Happy Tuesday, is everything on track?", "It's Wednesday, go go go!", "It's Thursday, why not have a good dinner tonight?", "Happy Friday, the weekend is coming.", "Wow Saturday, how would you like to celebrate it?", "It's Sunday, stay tuned for the upcoming great week. Are you ready for it?"] greeting = _(greetings[date.today().weekday()]) @app.route('/') def main(): return render_template("index.html", greeting=greeting) @app.route('/wechat') def wechat(): return render_template("wechat.html") @app.route('/faq') def faq(): return render_template("faq.html", greeting=greeting) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 if __name__ == "__main__": app.run();
else: return render_template("alert.html") @app.route('/searchpage', methods=['GET', 'POST']) def search(): if request.method == 'GET': return render_template('search.html') elif request.method == 'POST': name = request.form['Search'] conn = contact.query.filter(contact.name.like(name.capitalize() + '%')).all() return render_template('show.html', cont=conn) @app.route('/deletepage', methods=['GET', 'POST']) def delete(): if request.method == 'GET': return render_template('delete.html') elif request.method == 'POST': name = request.form['Name'] conn = contact.query.filter(contact.name == name.capitalize()).one() db.session.delete(conn) db.session.commit() return render_template('deletealert.html') if __name__ == "__main__": db.create_all() app.run(debug=True, port=8585)
@app.before_request def log_request(): logger = getLogger("netman.api") logger.info("{} : {}".format(request.method, request.url)) if logger.isEnabledFor(DEBUG): logging.getLogger("netman.api").debug("body : {}".format(repr(request.data) if request.data else "<<empty>>")) logging.getLogger("netman.api").debug("Headers : " + ", ".join(["{0}={1}".format(h[0], h[1]) for h in request.headers])) switch_factory = SwitchFactory(MemoryStorage(), ThreadingLockFactory()) switch_session_manager = SwitchSessionManager() NetmanApi().hook_to(app) SwitchApi(switch_factory, switch_session_manager).hook_to(app) SwitchSessionApi(switch_factory, switch_session_manager).hook_to(app) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Netman Server') parser.add_argument('--host', nargs='?', default="127.0.0.1") parser.add_argument('--port', type=int, nargs='?', default=5000) parser.add_argument('--session_inactivity_timeout', type=int, nargs='?') args = parser.parse_args() if args.session_inactivity_timeout: switch_session_manager.session_inactivity_timeout = args.session_inactivity_timeout app.run(host=args.host, port=args.port)
import time from flask import request from flask.app import Flask from flask.json import jsonify from flask_restful import Resource, Api class ttt(Resource): def post(self): # [WEB->RESTIF] RECEIVE PROCESS content = request.get_json(force=True) print request.remote_addr print request.method return "true" if __name__ == '__main__': app = Flask(__name__) api = Api(app) api.add_resource(ttt, '/ttt') app.run(host='0.0.0.0')
session["access_token"] = access_token return str(access_token) @app.route("/login") @app.route("/login/<id>/<pw>") def login(id=None, pw=None): print "id:%s, pw:%s" % (id, pw) payload = {'id': id, 'exp': datetime.utcnow() + timedelta(seconds=300)} token = jwt.encode(payload, 'my_secret', algorithm='HS256') html = "<h1>jwt 테스트</h1><hr>" html += '<a href=/only_member>회원만</a>' res = make_response(html) res.set_cookie('my_token', value=token) return res @app.route("/only_member") def only_member_page(): received_jwt = request.cookies['my_token'] payload = jwt.decode(received_jwt, 'my_secret') rv = make_response(jsonify(payload)) rv.headers['Content-Type'] = 'application/json' return rv if __name__ == '__main__': app.run(port=7778, debug=True)
re.findall(href_regexp, raw_response) response = make_response(raw_response) # copy response headers for header in url_response.headers: for header_prefix in PROXY_RESPONSE_HEADER_PREFIXES: if header.lower().startswith(header_prefix): # copy header response.headers[header] = url_response.headers[header] break return response if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", help="debug mode, pause on exception", action="store_true") parser.add_argument("-b", "--bind", help="bind address", default="0.0.0.0") parser.add_argument("-p", "--port", help="server port", default=8005, type=int) parser.add_argument("-i", "--inject", help="inject script", default=None) args = parser.parse_args() if args.inject: with open(args.inject) as f: PROXY_INJECT_SCRIPT = f.read() app.run(host=args.bind, port=args.port, debug=args.debug)
from flask.app import Flask from flask_restful import Api from controllers.captchacontroller import CaptchaController app = Flask(__name__) api = Api(app) api.add_resource(CaptchaController, '/captcha/') app.run(debug=True)
from flask.globals import request app = Flask(__name__) #访问根目录是响应home函数 @app.route('/', methods=['GET', 'POST']) def home(): return '<h1>Home</h1>' @app.route('/signin', methods=['GET', 'POST']) def signin_form(): return r'''<form action="/solvesign" method="post"> <p><input name="username"></p> <p><input name="password" type="password"></p> <p><button type="submit">Sign In</button></p> </form>''' @app.route('/solvesign', methods=['POST']) def sigin(): #从request对象中读取表单内容: if request.form['username'] == 'admain' and request.form[ 'password'] == '123456': return r'<h3>Hello Bob!</h3>' #使服务器运行 app.run()
# encoding: utf-8 """ @author: youfeng @file: main.py @time: 2018/11/16 下午10:39 """ from flask.app import Flask application = Flask(__name__) @application.route("/") def hello(): return "hello world!" if __name__ == '__main__': application.run()
finally: if con: con.close() def remove(pageid): con = None try: con = lite.connect(DATABASE) with con: con.rollback() cur = con.cursor() cur.execute("DELETE FROM page WHERE pageid = ?", (pageid,)) cur.execute("DELETE FROM medialinks WHERE pageid = ?", (pageid,)) cur.execute("DELETE FROM otherlinks WHERE pageid = ?", (pageid,)) con.commit() return "Successfully Removed" except lite.Error, e: return str(e) finally: if con: con.close() @nc4h.route('/remove_submission', methods=["POST"]) def remove_sub(): pageid = request.form['pageid'] message = remove(pageid) return render_template('mysubmissions.html',message=message) if __name__ == '__main__': nc4h.run(host='0.0.0.0',port=2000,debug=True)
from flask.app import Flask from flask import jsonify from flask_api import status app = Flask('delay-response-server') @app.route('/delay/v1/<int:delay_time>') def delay_response(delay_time: int): if not 0 <= delay_time <= 10: return jsonify({ 'error': 'delay time path parameter should be 0 ~ 10 seconds.' }), status.HTTP_400_BAD_REQUEST time.sleep(delay_time) return jsonify({ 'id': uuid.uuid1(), 'delayTime': delay_time, 'called_at': datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S,%f') }), status.HTTP_200_OK if __name__ == "__main__": app.run(host='0.0.0.0', port=5000 # debug=True )
def create_report(): rep = Report({"condition": "cough", "date": getTimestamp()}) db.session.add(rep) db.session.commit() for rep in Report.query.all(): print("ID: " + str(rep.report_id) + " condition: " + (rep.condition) + " date: " + str(rep.date)) return str(Report.query.all()) @app.route("/report-fetch") def fetch_all_reports(): reports = Report.query.all() for rep in reports: print("ID: " + str(rep.report_id) + " condition: " + (rep.condition) + " date: " + rep.date) return jsonpickle.encode(reports) if __name__ == '__main__': db.create_all() #create the schema using the alchemy context #create_report() app.run(port=7700) pass
try: if response.code == 200: if check_req_format(response): pbuff = response.read() msg = BargainingMessage.deserialize(pbuff) if not nego.already_received(msg): if msg.check_msg_fmt(NETWORK): nego.check_consistency(msg) nego.append(msg) nego_db_service.update_nego(session['nid'], nego) else: errors.append('Remote node returned an error') except: errors.append('A problem occurred while processing the message sent by the remote node') ''' Prepares rendering ''' params_tpl = {} params_tpl['errors'] = '' if len(errors) == 0 else '\n'.join(errors) params_tpl['wallet_blc'] = get_balance([negotiator.addr1]) params_tpl['chain'] = nego._msgchain params_tpl['completed'] = True if nego.status in {NEGO_STATUS_CANCELLED, NEGO_STATUS_COMPLETED} else False return render_template('negotiation.html', params_tpl=params_tpl) if __name__ == '__main__': # Comment/uncomment following lines to switch "production" / debug mode #app.run(host='0.0.0.0', port=8083) app.run(debug=True, port=8083)