def _runFlask(self, gw, port):
        """
        :param gw: Gateway
        :type gw: smsframework.Gateway.Gateway
        :return:
        :rtype:
        """
        # Init flask
        app = Flask(__name__)
        app.debug = True
        app.testing = True

        # Register gateway receivers
        gw.receiver_blueprints_register(app, prefix='/sms')

        # Stop manually
        @app.route('/kill', methods=['GET','POST'])
        def kill():
            func = request.environ.get('werkzeug.server.shutdown')
            if func is None:
                raise RuntimeError('Not running with the Werkzeug Server')
            func()
            return ''

        # Run
        app.run('0.0.0.0', port, threaded=False, use_reloader=False, passthrough_errors=True)
Exemple #2
0
class RootREST:

    def __init__(self, host, run_flask, port):
        self.host = host
        self.port = port
        self.run_flask = run_flask
        self.app = Flask(__name__)
        CORS(self.app,
             resources={
                 r'/*': {
                     'origins': '*',
                     'headers': ['Content-Type']
                 }
             }
        )
        #blueprintRest = BlueprintRest()
        self.app.register_blueprint(bp, url_prefix='/blueprint')
        #self.app.register_blueprint(Blueprint('blueprint', __name__), url_prefix='/blueprint')

        # Root service.
        @self.app.route('/')
        def landing():
            return core.landing_message()

        # Run Flask.
        if self.run_flask:
            self.app.run(host=self.host, port=self.port)
Exemple #3
0
def serve(py_exec=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")

    @app.route("/<name>")
    @app.route("/<name>/<season>/<episode>")
    def redirect_to(name, season=None, episode=None):
        interface = get_interface()
        command = "%s touchandgo.py \"%s\" " % (py_exec, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        command += "--daemon"
        print command
        process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
        sleep(10)
        port = 8888
        return redirect("http://%s:%s" % (interface, port))

    app.debug = True
    app.run(host="0.0.0.0")
Exemple #4
0
def server():
    from cherrypy import wsgiserver
    app = Flask(__name__)
    # app.config.from_object('config')

    @app.route("/")
    def index():
        return render_template("index.html")

    @app.route("/bar/")
    def bar():
        return render_template("bar.html")

    @app.route("/sleep/")
    def sleep():
        return render_template("sleep.html")

    @app.route("/up/")
    def up():
        return render_template("dcjsup.html")    

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    app.debug = True
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)
    d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
    server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8001), d)
Exemple #5
0
def start(application):
    """Start the web frontend"""

    # Make sure our views can access the main application
    global app
    app = application

    static_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        '../static/'
    )

    config = app.get_config()

    frontend = Flask(__name__, static_folder=static_path)

    # Make sure we crash if there's some bug in the frontend code, this is so
    # we'll find the bugs
    frontend.config['PROPAGATE_EXCEPTIONS'] = True

    frontend.add_url_rule('/', view_func=MainView.as_view('index'))
    frontend.add_url_rule('/data.json', view_func=DataView.as_view('data'))

    # Set up the route for static files
    @frontend.route('/static/<path:filename>')
    def send_static(filename):
        return send_from_directory(static_path, filename)

    frontend.run(host='0.0.0.0', port=config.http_port)

    return frontend
Exemple #6
0
class WebApp:
    def __init__(self, www, db_path):
        self.www = www
        self.db = db_connector.DB(db_path)
        self.html_dependencies()
        self.cache = cache.Cache(self.db)

    def start(self):
        host = self.www['host']
        port = self.www['port']
        static_folder = self.www['static_folder']
        template_folder = self.www['template_folder']
        debug = self.www['debug']

        self.app = Flask(__name__,
                         static_folder=static_folder,
                         template_folder=template_folder)

        router.RulesRouter(self.app, self.db, self.cache).configure()

        logger.info('craft-server-start')
        self.app.run(host=host, port=port, debug=debug, use_reloader=False)

    def stop(self):
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
            logger.error('craft-server-stop-error')
            raise RuntimeError('Not running with the Werkzeug Server')
        func()
        logger.info('craft-server-stop')

    def html_dependencies(self):
        deps = self.www['ext']
        dependencies.download(deps['path'], deps['file'])
Exemple #7
0
def start():
    """
    Start the Capo web server.
    """
    app = Flask('capolib.web')
    views.init_views(app)
    app.run()
Exemple #8
0
    def run(self):
        global MASTER
        app = Flask(__name__)

        @app.route("/")
        def index():
            return render_template('index.html')

        @app.route("/settings")
        def settings():
            settingsObj = {
                "connection": "ajax"
            }
            return jsonify(settingsObj)

        @app.route("/master/<string:value>")
        def master(value):
            global MASTER
            MASTER = float(value)
            return MASTER

        @app.route("/generator/<string:name>/<int:value>")
        def generator(name, value):
            generatorsByName[name] = value
            updateGenerators()
            return jsonify(generatorsByName)

        print "flask run"
        app.run(debug=False, use_reloader=False, threaded=True, host="0.0.0.0", port=4000)
Exemple #9
0
def run(password='', debug=False, host='127.0.0.1', port=8282):
    SECRET_KEY = os.environ.get('CCP_FLASK_KEY', False) or _random_secret_key()
    USERNAME = os.environ.get('CCP_FLASK_ADMIN_USER', False) or 'admin'
    PASSWORD = password or 'ciscoconfparse'
    app = Flask(__name__)
    app.config.from_object(__name__)
    app.run(host=host, port=port, debug=False)
Exemple #10
0
def challenge31_and_32_server(artificial_delay=0.002, key=Random.new().read(random.randint(16,64))):
    
    from flask import Flask, request, abort
    app = Flask(__name__)

    import logging
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

    @app.route("/")
    def main():
        msg = ascii_to_raw(request.args.get('msg'))
        user_supplied_tag = hex_to_raw(request.args.get('tag'))
        right_tag = hmac(key, msg, raw=True)
        for i in range(len(right_tag)):
            if right_tag[i] == user_supplied_tag[i]:
                time.sleep(artificial_delay)  
            else:
                abort(500)
        return 'ok'

    @app.route("/answer")
    def answer():
        msg = ascii_to_raw(request.args.get('msg'))
        right_tag = hmac(key, msg, raw=True)
        return raw_to_hex(right_tag) 

    app.run(threaded=True)
Exemple #11
0
def start():
    """start the flask service"""

    # create app
    app = Flask(__name__)
    app.debug = True


    #Data comes into this method:
    #'sessionStartTime' is the number of seconds since 1970 when the experiment started
    #'data' is the latest raw data, served up as a csv (each line contains up to 8 channels)
    @app.route('/data', methods=['POST'])
    def saveRatingsToGene():
        print "starting"
        print request.form

        data = request.form['data']
        sessionStartTime = request.form['sessionStartTime']

        #Do we already have a DB entry for this?
        experiment_obj = db.experiments.find_one({"sessionStartTime": sessionStartTime})

        #The data is coming in as a text CSV.
        rows = data.split('\n')
        for row in rows:
            channels = row.split(',')
            #somehow put this data into a mongo object


        return "OK"

    #This server must expose URLs to allow the user to dload the csv from the server
    #Flask gives us what we need to dload files. This sample code might be overly complicated
    #As it is built for streaming large files, which we don't necessarily need
    #http://flask.pocoo.org/docs/patterns/streaming/
    @app.route('/large.csv')
    def generate_large_csv():
        def generate():
            for row in iter_all_rows():
                yield ','.join(row) + '\n'
        return Response(generate(), mimetype='text/csv')

    # This is where we should be able to display a list of all experiments in the mongodb
    # And use them to fill in a template (.tpl file) to allow either dloaded files
    # or perhaps, even visualized on the screen
    # Very excited about this plotting library (if it's easy to implement):
    # http://code.shutterstock.com/rickshaw/
    @app.route('/', methods=['GET'])
    def hello_world():

        experiments = db.experiments.find() #get all

        for experiment in experiments:
            print "Yep we see an experiment"

        print "yep working"


    # let's go!
    app.run()
Exemple #12
0
def preview_runserver(args):
    output_dir = os.path.abspath(args.output)
    app = Flask(__name__)

    # TODO 3xx redirects
    # TODO 404 page
    # TODO 410 page
    @app.route('/')
    @app.route('/<path:path>')
    def send_file(path=''):
        filename = os.path.basename(path)
        if filename == '':
            path = '%sindex.html' % path
        root, ext = os.path.splitext(path)
        if ext == '':
            path = '%s.html' % path
        print('->', path)
        return send_from_directory(output_dir, path)

    @app.after_request
    def add_header(response):
        response.cache_control.max_age = 0
        return response

    app.run(port=3567)
def webService(server):
    from flask import Flask, jsonify

    app = Flask(__name__)

    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

    @app.route('/')
    def index():
        print server.activeRelays
        return "Relays available: %s!" % (len(server.activeRelays))

    @app.route('/ntlmrelayx/api/v1.0/relays', methods=['GET'])
    def get_relays():
        relays = []
        for target in server.activeRelays:
            for port in server.activeRelays[target]:
                for user in server.activeRelays[target][port]:
                    if user != 'data' and user != 'scheme':
                        protocol = server.activeRelays[target][port]['scheme']
                        isAdmin = server.activeRelays[target][port][user]['isAdmin']
                        relays.append([protocol, target, user, isAdmin, str(port)])
        return jsonify(relays)

    @app.route('/ntlmrelayx/api/v1.0/relays', methods=['GET'])
    def get_info(relay):
        pass

    app.run(host='0.0.0.0', port=9090)
Exemple #14
0
class BaseApp(object):
    def __init__(self, *args, **kwargs):
        self.app = Flask(__name__)

    def run(self, *args, **kwargs):
        self.app.run(*args, **kwargs)
        self.db = MongoEngine(self.app)
Exemple #15
0
  def serve(self):
    """
    Start serving.
    This is blocking.
    """
    logger.info("Serving.")
    app = Flask(__name__)

    @app.route("/")
    def hello():
      return "Hello. This is a link server."

    @app.route("/stats")
    def stats():
      return "No stats."

    @app.route("/event/<event_id>")
    def event(event_id):
      logger.info("Received event {}".format(event_id))
      happened = self._execute(event_id)
      if happened:
        return "Oooh! That just happened."
      else:
        return "I'm afraid that didn't happen, Dave."

    app.run()
Exemple #16
0
class FyPress():
    def __init__(self, config, manager=False):
        from flask.ext.babel import Babel
        from utils.mysql import FlaskFyMySQL

        self.prepared = False
        self.config = config
        self.app = Flask(
            __name__,
            template_folder=self.config.TEMPLATE_FOLDER,
            static_folder=self.config.STATIC_FOLDER
        )
        self.app.config.from_object(config)
        self.app.wsgi_app = ProxyFix(self.app.wsgi_app)
        self.babel = Babel(self.app)
        self.db    = FlaskFyMySQL(self.app)

        if not manager:
            self.prepare()

    def run(self, host='0.0.0.0', port=5000):
        if self.prepared == False:
            self.prepare()
        self.app.run(host=host, port=port, debug=self.config.DEBUG)

    def prepare(self):
        local.fp = self
        self.prepared = True

        @self.app.before_request
        def before_request():
            g.start = time.time()
            
        if self.config.DEBUG:
            @self.app.after_request
            def after_request(response):
                diff = time.time() - g.start
                if (response.response):
                    response.headers["Execution-Time"] = str(diff)
                return response

        self.app.add_url_rule(self.app.config['UPLOAD_DIRECTORY_URL']+'<filename>', 'FyPress.uploaded_file', build_only=True)
        self.app.wsgi_app = SharedDataMiddleware(self.app.wsgi_app, {self.app.config['UPLOAD_DIRECTORY_URL']: self.app.config['UPLOAD_DIRECTORY']})

        self.blueprint()

    def blueprint(self):
        ### Blueprints ###
        from user import user_blueprint
        from admin import admin_blueprint
        from public import public_blueprint

        ### Load Blueprints ###
        self.app.register_blueprint(user_blueprint)
        self.app.register_blueprint(admin_blueprint)
        self.app.register_blueprint(public_blueprint)

    @staticmethod
    def uploaded_file(filename):
        return send_from_directory(self.app.config['UPLOAD_DIRECTORY'], filename)
Exemple #17
0
class LabyrinthServer(object) :
    def __init__(self, configFile) :
        self.app = Flask(__name__)
        self.api = Api(self.app)
        logging.debug("opening config file %s for reading" % configFile)
        try :
            fp = open(configFile, 'r')
            self.config = json.load(fp)
            fp.close()
        except IOError :
            logging.critical("Unable to open the config file %s for reading" % configFile)
            exit(10)
        except ValueError :
            logging.critical("Unable to read the JSON object in the config file %s" % configFile)
            exit(10)

        try :
            for endpoint in self.config['endpoints'] :
                if self.config['endpoints'][endpoint] == "JobRunner" :
                    self.api.add_resource(JobRunner, endpoint)
                    logging.info("Created JobRunner endpoint for "+endpoint)
                elif self.config['endpoints'][endpoint] == "JobManager" :
                    self.api.add_resource(JobManager, endpoint)
                    logging.info("Created JobManager endpoint for "+endpoint)
                else :
                    logging.error("Unknown class for endpoint '%s'.  No Class '%s' exists" % (endpoint,self.config['endpoints'][endpoint]))
        except KeyError :
            logging.critical("There is a configuration problem with the endpoints in the file '%s'" % configFile)
            exit(10)

        try :
            self.app.run(port=self.config['port'])
        except KeyError :
            logging.critical("Server Configuration does not specify a port, defaulting to port 5000")
            self.app.run(port=5000)
def server():
    from cherrypy import wsgiserver
    app = Flask(__name__, static_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static'))
    # app = Flask(__name__)

    @app.route('/data.json')
    # @crossdomain(origin='*')
    def data_json():
        s = json.dumps([json.loads(s) for s in 
            list(redis.smembers('fitbit'))])
        return s

    @app.route('/')
    def index_html():
        context = {
        }
        env = Environment(loader=FileSystemLoader('templates'))
        return env.get_template('index.html').render(context)
    
    @app.route('/sleep/')
    def sleep():
        context = {
        }
        env = Environment(loader=FileSystemLoader('templates'))
        return env.get_template('index.html').render(context)

    print 'Listening :8001...'
    d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
    port = int(os.environ.get("PORT", 5000))    
    app.run(host='0.0.0.0', port=8000, use_debugger=True)
    server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8001), d)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Exemple #19
0
def FlaskRunner(q):

    queue = q
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    def gen():
        while True:
            if not queue.empty():
                frameaux = queue.get()
                if frameaux is not None:
                    ret, jpeg = cv2.imencode('.jpeg', frameaux)
                    frame = jpeg.tostring()

                if frame is not None:
                    yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
            #Slow down the streaming
            time.sleep(0.15)

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

    app.run(host='0.0.0.0', port=7777, debug=False)
Exemple #20
0
def serve(directory='.', readme_file='README', port=None):
    """Starts a server to render the readme from the specified directory."""

    # Get the README filename
    filename = find_readme(directory, readme_file)
    if not filename:
        raise ValueError('No %s file found at %s' % ('README' if readme_file == 'README' else repr(readme_file), repr(directory)))

    # Flask application
    app = Flask('grip')
    app.config.from_pyfile('default_config.py')
    app.config.from_pyfile('local_config.py', silent=True)

    # Get styles from style source
    @app.before_first_request
    def retrieve_styles():
        if not app.config['STYLE_URL_SOURCE'] or not app.config['STYLE_URL_RE']:
            return
        styles = _get_styles(app.config['STYLE_URL_SOURCE'], app.config['STYLE_URL_RE'])
        app.config['STYLE_URLS'] += styles
        if app.config['DEBUG_GRIP']:
            print ' * Retrieved %s style URL%s' % (len(styles), '' if len(styles) == 1 else 's')

    # Set overridden config values
    if port is not None:
        app.config['PORT'] = port

    # Views
    @app.route('/')
    def index():
        return render_page(read_file(filename), filename, app.config['STYLE_URLS'])

    # Run local server
    app.run(app.config['HOST'], app.config['PORT'], debug=app.debug, use_reloader=app.config['DEBUG_GRIP'])
Exemple #21
0
def runWebserver( context={}, plot_funcs = {}, database_file="database.sqlite", 
                   open_browser=False, debug=True ):
    """Runs a small local webserver using the flask module ( pip3 install flask ) serving the report. 
       When refreshing in the browser the report is updated."""
    from flask import Flask
    from flask import render_template, make_response, send_from_directory
    
    context['database_file'] = database_file
    
    app = Flask(__name__)
    app.debug=True
    setupFlaskApp(app, context=context, plot_funcs=plot_funcs, database_file=database_file )
    
    @app.route("/")
    def main_route():
        reports = [ n[2:-5] for n in glob( "t_*.html") ]
        return render_template( "waLBerla/report_overview.html", reports=reports, **context )

    @app.route("/<template_name>")
    def report_route(template_name):
        template_name = "t_" + template_name + ".html"
        return render_template( template_name, **context )
    
    @app.route("/pdfs/<path:filename>" )
    def pdf_route( filename ):
        return send_from_directory( os.path.join( os.getcwd() , pdf_output_dir), filename)
    
    if open_browser:
        import webbrowser
        webbrowser.open('http://127.0.0.1:5000/')

    app.run( debug=debug )
Exemple #22
0
    def video_stream_loop(self):
        flaskApp = Flask(__name__)
        running = False
        
        @flaskApp.route('/')
        def index():
            return render_template('index.html')
    
        def gen():
            self.frame_count = 0
            while (self.stream_on):
                while (not self.new_stream_image):
                    time.sleep(0.001)
                self.new_stream_image = False
                if (self.frame_count % self.reduse_stream_fps_by_a_factor == 0):
                    yield (b'--frame\r\n'
                        b'Content-Type: image/jpeg\r\n\r\n' + self.stream_image_jpeg.tostring() + b'\r\n\r\n')
                    self.have_yield = True
                self.frame_count += 1
                

        @flaskApp.route('/video_feed')
        def video_feed():
            return Response(gen(),
                mimetype='multipart/x-mixed-replace; boundary=frame')
        
        flaskApp.run(host='0.0.0.0', port=self.streaming_port, debug=False, use_reloader=False)
Exemple #23
0
def run_webserver(destination_root_dir):
    """ Run a local """
    destination_root_dir = destination_root_dir
    if destination_root_dir.startswith("/"):
        destination_root_dir = destination_root_dir[1:]

    if destination_root_dir.endswith("/"):
        destination_root_dir = destination_root_dir[:-1]

    app = Flask(__name__)

    @app.route("/")
    @app.route("/<path:filename>")
    def serve_static_html(filename="index.html"):
        """ Serve static HTML files

        :type filename: str
        :param filename: Path to the static HTML file
        """
        if filename.startswith(destination_root_dir):
            filename = filename.replace("{}/".format(destination_root_dir), "")
            return redirect("/{}".format(filename))

        response = make_response(send_from_directory("/{}".format(destination_root_dir), filename))
        response.cache_control.no_cache = True

        return response

    app.run()
Exemple #24
0
class KodemonAPI():
	def __init__(self, SERVER_NAME='localhost:4000', db_conn_string='sqlite:///AppData/Kodemon.sqlite', debug=True):
		self.app = Flask(__name__)
		self.app.debug = debug

		self.app.config['SERVER_NAME'] = SERVER_NAME
		
		self.app.config['SQLALCHEMY_DATABASE_URI'] = db_conn_string
		self.db = db
		
		self.db.init_app(self.app)
		self.set_routes()

	def run(self):
		self.app.run()

	def set_routes(self):
		@self.app.route("/", methods=['GET'])
		def index():
			return self.app.send_static_file('index.html')


		api_prefix = '/api/v1/'
		
		@self.app.route(api_prefix + 'messages/', methods=['GET'])
		def messages():
			return 'This will return all messages'

		@self.app.route(api_prefix + 'messages/keys/', methods=['GET'])
		def message_keys():
			result = []
			for m in MessageBase.query.all():
				if m.key not in result:
					result.append(m.key)

			return json.dumps(result)

		@self.app.route(api_prefix + 'messages/execution_times/<key>', methods=['GET'])
		def message_execution_times(key):
			#get query parameters (may be None)
			start_time, end_time = request.args.get('start_time'), request.args.get('end_time')

			if start_time:
				start_time = int(start_time)
			else:
				start_time = 0

			if end_time:
				end_time = int(end_time)
			else:
				end_time = sys.maxint

			#Get execution times
			times = []
			for m in MessageBase.query.filter_by(key=key):
				if start_time <= m.timestamp <= end_time:
					times.append({'execution_time': m.execution_time, 'timestamp': m.timestamp, 'token': m.token})

			result = {'key': key, 'execution_times': times}
			return json.dumps(result)
Exemple #25
0
def getResult(temp):
    result_final=[]
    app = Flask(__name__)
    client = MongoClient()
    collection = client.test_database.collection_name
    preprocessInputData()
    db = client.test_database
    posts = db.posts
    @app.route('/',methods=['GET'])
    def test():
        return jsonify({'message': "it works"})

    @app.route('/search',methods=['GET'])
    def returnAll():
        results=[]
        query = request.args.get('q')
        doc=db.test_database.find();
        for eachEntry in doc:
            if query in eachEntry.keys():
                results.append(eachEntry[query])
        if len(results) == 0:
            results=findTopResultsForQuery(query)
            for each in results:
                db["test_database"].insert_one({query:each})
        return jsonify({"results":results})

    @app.errorhandler(404)
    def page_not_found(error):
        return jsonify({'404 err message': "enter query using http://127.0.0.1:5000/search?q=QUERY"})

    if __name__ == '__main__':
        app.run(debug=True)
Exemple #26
0
class RestServer(multiprocessing.Process):
    def __init__(self, host, port, smoker_daemon):
        """
        :param host: host to bind the server to"
        :type host: string
        :param port: port to bind the server to"
        :type port: int
        :param smoker_daemon: instance of the smoker daemon
        :type smoker_daemon: smokerd.Smokerd
        """
        self.host = host
        self.port = port
        self.app = Flask(__name__)

        self.api = Api(self.app)
        self.api.add_resource(About, '/')
        self.api.add_resource(Plugins, '/plugins', '/plugins/')
        self.api.add_resource(Plugin, '/plugins/<string:name>',
                              '/plugins/<string:name>/')
        self.api.add_resource(Processes, '/processes', '/processes/')
        self.api.add_resource(Process, '/processes/<int:id>',
                              '/processes/<int:id>/')

        global smokerd
        smokerd = smoker_daemon

        super(RestServer, self).__init__()
        self.daemon = True

    def run(self):
        setproctitle.setproctitle('smokerd rest api server')
        self.app.run(self.host, self.port)
Exemple #27
0
class app:
    """
    """

    controller_list = {}

    def __init__(self, name):
        self.app = Flask(name)
        self.app.debug = True
        self.app.secret_key = "this is a key"
        # app.run(host='0.0.0.0')

    def run(self, port):
        for k, v in self.controller_list.iteritems():
            print "Start Controller: %s" % (k)

        self.app.run(host="0.0.0.0", port=port)

    def add_controller(self, controller):
        self.controller_list[controller.name] = controller
        for k, v in controller.function_list.iteritems():
            route_path = "/" + controller.name + k
            if v.type == 1:
                route_path = "/" + controller.name + k + "/<path:url_var>"
            print "Reg function: %s" % (route_path)

            self.app.add_url_rule(route_path, None, v.func, **v.options)
Exemple #28
0
class RootREST:

    def __init__(self, host, run_flask):
        self.host = host
        self.run_flask = run_flask
        self.app = Flask(__name__)
        CORS(self.app,
             resources={
                 r'/*': {
                     'origins': '*',
                     'headers': ['Content-Type']
                 }
             }
        )
        self.app.register_blueprint(bp, url_prefix='/blueprint')

        # Root service.
        @self.app.route('/', methods=['GET'])
        def say_hello_service():
            return say_hallo()

        # Root service.
        @self.app.route('/<name>/', methods=['GET'])
        def say_hello_to_guest_service(name):
            return say_hallo(name)

        # Run Flask.
        if self.run_flask:                              # pragma: no cover
            self.app.run(host=self.host, debug=True)    # pragma: no cover
Exemple #29
0
def run_admin(host, port, db, password, listen):
    conn = redis.Redis(host, int(port or 6379), int(db or 0), password)
    tiger = TaskTiger(setup_structlog=True, connection=conn)
    app = Flask(__name__)
    admin = Admin(app, url='/')
    admin.add_view(TaskTigerView(tiger, name='TaskTiger', endpoint='tasktiger'))
    app.run(debug=True, port=int(listen or 5000))
def web_view():
    "Setup the webview"
    app = Flask("civic_api_client")

    @app.route("/")
    def template_home():
        return render_template("home.html")

    @app.route("/evidence-items")
    def evidence_items():
        eil1 = EvidenceItemsLister(sys.argv[2:])
        eil1.parse_args()
        eil1.create_invalid_eis_list()
        invalid_eis = eil1.get_invalid_eis()
        return render_template("evidence-items.html", invalid_eis=invalid_eis)

    @app.route("/variants")
    def variants():
        vl1 = VariantsLister(sys.argv[2:])
        vl1.parse_args()
        vl1.create_filtered_variants_list()
        filtered_variant_details = vl1.get_filtered_variant_details()
        return render_template("variants.html", filtered_variant_details=filtered_variant_details)

    app.run(debug=True)
Exemple #31
0
        {
            'name': '数学分析',
            'size': 4,
            'url': '/book/2',
        },
        {
            'name': '软件工程',
            'size': 5,
            'url': '/book/3',
        },
    ]
    for c in data['children']:
        if c['name'] == u'工学':
            for cc in c['children']:
                if cc['name'] == u'计算机科学与技术':
                    for ccc in cc['children']:
                        if ccc['name'] == u'计算机软件与理论':
                            ccc.pop('url')
                            ccc.pop('size')
                            ccc['children'] = cs
                            break
                    break
            break
    return jsonify(data)


if __name__ == '__main__':
    app.secret_key = os.urandom(12)
    db = DataBase()
    app.run(debug=True, host='localhost', port=8088)
Exemple #32
0
        status = "RUNNING" if random.uniform(0, 1) > 0.25 else "DOWN"
        sql_query = f"INSERT INTO {plant} (time, status) VALUES ('{time}', '{status}')"

        self.cur.execute(sql_query)
        self.con.commit()

    def list_entries(self):
        self.cur.execute("SELECT * FROM plant_1")
        result = self.cur.fetchall()

        return result

db = Database()

@app.route('/')
def entries():
    return render_template('entries.html', result=db.list_entries(), content_type='application/json')

@app.route('/acquire', methods=['GET', 'POST'])
def acquire():
    name = "plant_1"
    db.create_table(name, ["entry INT NOT NULL AUTO_INCREMENT", "time VARCHAR(255)", "status VARCHAR(255)", "PRIMARY KEY (entry)"])

    db.generate_entry(name)

    return redirect('/')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000')

Exemple #33
0
    #subprocess.call(command)
    p = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
    output = p.communicate()
    output = output[0].decode('utf-8')
    output = output.split('\r\n')
    print('this is OUTPUT', output)
    return jsonify(output[1:4])

# getting info about eyes - to call - localhost:5000/run_eye/<img_id> where
# img_id is the name of the image file without extension
@app.route('/run_eye/<img_id>', methods=['GET'])
def run_eye(img_id):
    command = r'C:\Users\TengriLab\Desktop\DOCUMENTATION\api_test\test_live_ocv34_estimates\x64\Release\eye\test_live.exe C:\Users\TengriLab\Desktop\DOCUMENTATION\api_test\test_live_ocv34_estimates\x64\Release\\' + img_id + '.ppm'
    #subprocess.call(command)
    p = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
    output = p.communicate()
    output = output[0].decode('utf-8')
    output = output.split('\r\n')
    print('this is OUTPUT', output)
    return jsonify(output[1:3])


@app.route('/liveness', methods=['POST'])
def add_liveness():
    liveness.append(request.get_json())
    return jsonify(liveness)


if __name__ == '__main__':
    app.run(threaded=True)
Exemple #34
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    hack by djj -_,- | good luck!
"""
from flask import Flask, redirect, url_for

from api import sample_api
from selector import selector

app = Flask(__name__)
app.debug = True
app.secret_key = 'hahahahahahahaha'
app.port = 11203
app.register_blueprint(sample_api)
app.register_blueprint(selector)


@app.route('/', methods=['GET'])
def index():
    return redirect(url_for('selector'))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9999)
	
	#based on the foodname we are sent through the url, we retrieve information from the database and compare the name with all names retrieved, if the name is matched, we render all its values on this page
	query = 'select food.foodname, food.*, nutrients.*, round(avg(ratings.rating),1), count(ratings.rating) from food join nutrients on food.id = nutrients.foodid left join ratings on food.id = ratings.foodid group by food.id'
	results = cursor.execute(query)
	foods = []
	print(foodname)
	for row in results:
		if(row[0] == foodname):
			foods.append(row)
			return render_template("results.html", items = foods, form = form, ratings = ratings)
	return "Cant Find it are you sure that food exists"
	connection.close()

@app.route('/api/<foodid>', methods = ['GET'])
def api(foodid):
	connection = sqlite3.connect('data.db')
	cursor = connection.cursor();
	query = 'Select * from Food WHERE ID = {}'.format(int(foodid))
	ratingtable = cursor.execute(query)
	foodtable = []
	dict = {}
	for eachrow in ratingtable:
		dict['{}'.format(eachrow[1])] = {'id': '{}'.format(eachrow[0]),'foodname': "{}".format(eachrow[1]),'ingredients': "{}".format(eachrow[2]),'shortdesc': "{}".format(eachrow[3]),'scientificname': "{}".format(eachrow[4]),'commercialName': "{}".format(eachrow[5]),'lastIngUpdate':"{}".format(eachrow[6]),'DBsource': "{}".format(eachrow[7]),'Groupname': "{}".format(eachrow[8]),'manu': "{}".format(eachrow[9])}

	return jsonify({'foodinfo': dict})
	connection.close()

#	return render_template("search.html",options = food, form = form)
if __name__ == '__main__':
	app.run(debug = True, host = 'localhost')
Exemple #36
0
    name = request.json.get('name')
    text = request.json.get('text')

    if not isinstance(request.json.get('name'), str) or not isinstance(
            request.json.get('text'), str):
        return abort(400)
    if not name or not text:
        return abort(400)

    new_message = {'name': name, 'text': text, 'time': time.time()}
    db.append(new_message)
    return {'OK': True}


@app.route("/messanges")
def get_messange():
    try:
        after = float(request.args.get('after', 0))
    except ValueError:
        return abort(400)

    messanges = []
    for messange in db:
        if messange['time'] > after:
            messanges.append(messange)
    return {'messanges': messanges}


app.run()
Exemple #37
0
    node_obj = [{
        "id": node.id,
        "name": node.name,
        "isOpen": False,
        "children": []
    }]
    return jsonify(node_obj)


# GET node's childeren by parent_id
@app.route('/<parent_id>/children')
def get_node_children(parent_id):
    edges = db.session.query(
        EdgesTable, NodesTable).filter_by(parent_id=parent_id).outerjoin(
            NodesTable, EdgesTable.child_id == NodesTable.id).all()
    children = []
    for edge in edges:
        node = {
            "id": edge[1].id,
            "name": edge[1].name,
            "isOpen": False,
            "children": []
        }
        children.append(node)

    return jsonify(children)


if __name__ == '__main__':
    app.run(debug=True)
Exemple #38
0
app = Flask(__name__)
cache = redis.Redis(host='redis-lb', port=6379)


def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

def get_my_ip():
    return request.remote_addr


@app.route('/')

def hit():
    ip = get_my_ip()
    count = get_hit_count()
    return 'User Address : %s .' %ip + 'Hits: %s .\n'% int(count)


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

                   "coconut"]  # Must match what weights file was trained on

        result = None
        try:
            counttrees(classes, temp, args.darknetpath, imagepath, args.cfg,
                       args.weights, args.out, args.err)
            result = untile(classes, temp, size[0], size[1], 0.0)
        except Exception as ex:
            print(ex)
            return render_template("error.htm", text=str(ex))
        finally:
            if True:  # Switch to False for debugging by inspecting the contents of the temp folder
                shutil.rmtree(temp)
            else:
                print("not deleting " + temp)

        with open(results + "/predictions.json", "w") as outfile:
            json.dump(result, outfile)

        return render_template("result.htm",
                               kind="result",
                               ident=ident,
                               caveat=args.caveat,
                               samples=get_samples())
    else:
        return render_template("error.htm", text="Image required")


if __name__ == "__main__":
    app.run(host="0.0.0.0")
Exemple #40
0
        Owner=int(request.form['Owner'])
        Fuel_Type_Petrol=request.form['Fuel_Type_Petrol']
        if(Fuel_Type_Petrol=='Petrol'):
                Fuel_Type_Petrol=1
                Fuel_Type_Diesel=0
        else:
            Fuel_Type_Petrol=0
            Fuel_Type_Diesel=1
        Year=2020-Year
        Seller_Type_Individual=request.form['Seller_Type_Individual']
        if(Seller_Type_Individual=='Individual'):
            Seller_Type_Individual=1
        else:
            Seller_Type_Individual=0
        Transmission_Mannual=request.form['Transmission_Mannual']
        if(Transmission_Mannual=='Mannual'):
            Transmission_Mannual=1
        else:
            Transmission_Mannual=0
        prediction=model.predict([[Present_Price,Kms_Driven,Owner,Year,Fuel_Type_Diesel,Fuel_Type_Petrol,Seller_Type_Individual,Transmission_Mannual]])
        output=round(prediction[0],2)
        if output<0:
            return render_template('index.html',prediction_texts="Sorry you cannot sell this car")
        else:
            return render_template('index.html',prediction_text="You Can Sell The Car at {}".format(output))
    else:
        return render_template('index.html')

if __name__=="__main__":
    app.run(debug=True, port=5000)
Exemple #41
0
import cv2

app = Flask("recognition-service")


@app.route('/train', methods=['POST'])
def handle_extract_face_features():
    face = ImageUtils.decode_image_buffer(
        bytearray(request.json['face']['data']))
    aligned_face = RecogitionService.align_face(face)
    face_features = RecogitionService.extract_features(aligned_face)

    return jsonify({"model": list(face_features)})


@app.route('/recognize', methods=['POST'])
def handle_recognize_face_from_features():
    features = np.array(request.json['model'])
    face_to_recognize = ImageUtils.decode_image_buffer(
        bytearray(request.json['face']['data']))
    aligned_face = RecogitionService.align_face(face_to_recognize)
    face_to_recognize_features = RecogitionService.extract_features(
        aligned_face)
    are_same = RecogitionService.recognize(features,
                                           face_to_recognize_features)

    return jsonify({"areSame": are_same})


app.run(port=4003)
import os
from twilio.rest import TwilioRestClient
from flask import Flask, request, render_template

twilio_account_sid = ''
twilio_auth_token = ''
twilio_from_number = ''
filepicker_api_key = ''

app = Flask(__name__)
client = TwilioRestClient(twilio_account_sid, twilio_auth_token)


@app.route("/", methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        client.sms.messages.create(
            to=request.form['phone_number'],
            from_=twilio_from_number,
            body="Check this out: %s?dl=false" % request.form['file'])
    fp_key = filepicker_api_key
    return render_template('simple.html', filepicker_api_key=fp_key)


if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.debug = True
    app.run(host='0.0.0.0', port=port)
Exemple #43
0
from flask import Flask
import utils
import os
from datetime import datetime

app = Flask(__name__)

@app.route("/<url>/<frame_by_frame_flag>")
def hello(url, frame_by_frame_flag):
    name = f"out.txt"
    gotAt = datetime.now().strftime('%M:%S.%f')
    print(f"{gotAt},", file=open(name, "a"), end="")
    utils.downloadVideo(f'https://www.youtube.com/watch?v={url}')
    utils.processVideo('temp.mp4', frame_by_frame_flag)
    processedAt = datetime.now().strftime('%M:%S.%f')
    print(f"\nfinished at: {processedAt}\n")
    print(f"{processedAt}", file=open(name, "a"))
    return f"Got requisition at: {gotAt}"

if __name__ == "__main__":
    # Only for debugging while developing
    app.run(host='0.0.0.0', debug=True, port=80)
Exemple #44
0
            logger.info("Successfully found an object to delete.")
            json_handler.delete_from_json(delete_type, obj)
            break

@app.route('/index')
def index():
    """renders the html form and listens for user trying to delete an object."""
    json_handler.get_user_input()
    # deleting alarm/notification
    if "alarm_item" in str(request.url) or "notif" in str(request.url):
        delete_an_object()
    return fill_out_the_form()


def run_sched() -> None:
    """Starts a scheduler."""
    SCHED.run()


@app.route("/")
def form():
    """Renders the html form for the homepage."""
    return fill_out_the_form()


if __name__ == '__main__':
    logger.info("Start app: refresh notifications and reschedule alarms.")
    json_handler.save_new_notifications()
    schedule_all_alarms()
    app.run(debug=False, use_reloader=False)
Exemple #45
0
class MockServer:

    def __init__(self, numServiceNodes):
        self.app = Flask('lokid-rpc-mock')
        #self.app.config['SECRET_KEY'] = os.urandom(16)
        # populate service nodes
        self._serviceNodes = dict()
        for n in range(numServiceNodes):
            self.makeSNode("svc-%03d" % n)

        self._handlers = {
            'lokinet_ping': self._lokinet_ping,
            'get_n_service_nodes' : self._get_n_service_nodes,
            'get_service_node_privkey' : self._get_service_node_privkey
        }
        #digest = HTTPDigestAuth(realm='lokid')
    
        @self.app.route('/json_rpc', methods=["POST"])
        def _jsonRPC():
            j = request.get_json()
            method = j['method']
            snode = None
            if 'authorization' in request.headers:
                user = b64decode(request.headers['authorization'][6:].encode('ascii')).decode('ascii').split(':')[0]
                self.app.logger.error(user)
                if len(user) > 0:
                    snode = self._serviceNodes[user]
            result = self._handlers[method](snode)
            if result:
                resp = {'jsonrpc': '2.0', 'id': j['id'], 'result': result}
                return jsonify(resp)
            else:
                r = make_response('nope', 401)
                r.headers['www-authenticate'] = 'basic'
                return r
        def after(req):
            req.content_type = "application/json"
            return req
        self.app.after_request(after)

    def _get_n_service_nodes(self, our_snode):
        return {
            'block_hash' : 'mock',
            'service_node_states' : self.getSNodeList()
        }
    
    def _get_service_node_privkey(self, our_snode):
        if our_snode is None:
            return None
        return {
            'service_node_ed25519_privkey': our_snode.seed()
        }

    def _lokinet_ping(self, snode):
        return {
            'status' : "OK"
        }
    
    def run(self):
        """
        run mainloop and serve jsonrpc server
        """
        self.app.run()
    
    def makeSNode(self, name):
        """
        make service node entry
        """
        self._serviceNodes[name] = SVCNode()


    def getSNodeList(self):
        l = list()
        for name in self._serviceNodes:
            l.append(self._serviceNodes[name].toJson())
        return l
Exemple #46
0
    """
 
    df_test = pd.read_csv(request.files.get("file"))
    prediction=estimator.predict(df_test)
    
    return str(list(prediction))
    # try http://0.0.0.0:8000/apidocs
    
@app.route('/predict_json/', methods=['GET','POST'])
def predict_from_json():
    
    # json input
    x = request.get_json()
    
    # convert x to DataFrame
    col = ['age','sex','bmi','children','smoker','region']
    x = pd.DataFrame(data=[x],columns=col)
        
    # make prediction
    prediction = estimator.predict(x)
    response = json.dumps({'prediction':list(prediction)})
    print(response)
    return response
    # try with postman
    # or curl --location --request POST '0.0.0.0:8000/predict_json/' --header 'Content-Type: application/json' --data-raw '[33,"female",18.36,0,"no","southeast"]'

if __name__=='__main__':
    app.run(host='0.0.0.0',port=8000)
    
    

    # return jsonify({"cards": cards_list})

    return jsonify(DATA["cards"])

@app.route("/add-card", methods=["POST"])
def add_card():
    """Add a new card to the DB."""

    name = request.form.get('name')
    skill = request.form.get('skill')

    # new_card = Card(name=name, skill=skill)
    # db.session.add(new_card)
    # db.session.commit()

    DATA["cards"].append({"name":name, "skill":skill, "imgUrl": ""}) 

    return jsonify({"success": True})

@app.route("/cards-jquery")
def show_cards_jquery():
    return render_template("cards-jquery.html")



if __name__ == "__main__":
  # connect_to_db(app)
    app.run(debug=True, host='0.0.0.0')
@application.route("/superpacs/sankey")
def superpacs_sk_view():
    return render_template("superpacs_sk.html")


@application.route("/candphoto/<cand_id>", methods=["GET"])
def get_cand_photo(cand_id):
    cand_id = str(cand_id)[:10]
    if not cand_id.isalnum():
        return abort(401)
    return backend.get_cand_photo(cand_id)


@application.route("/electionppts/<cand_id>", methods=["GET"])
def get_elect_ppts(cand_id):
    cand_id = str(cand_id)[:10]
    if not cand_id.isalnum():
        return abort(401)
    return jsonify(backend.get_most_recent_election(cand_id))


if __name__ == "__main__":
    with application.app_context():
        backend.get_pg()
    if len(sys.argv) > 1:
        application.run(host="0.0.0.0", port=int(sys.argv[1]))
    else:
        application.run(host="0.0.0.0")
    #app = index2.init_dash(application)
    #application.run(host="0.0.0.0")
Exemple #49
0
                        tampil("Type yang anda input tidak ada")
        except IndexError:
                tampil(update, """/meninggal {type} {nama negara/provinsi}

Type:
  local  = wilayah indonesia
  global = seluruh dunia

Negara: nama negara
Provinsi: nama provinsi indonesia
""")

@app.route("/")
def index():
#	up = Updater("1081432210:AAGBmcqslDCMvLIW2nmG8l8rAvVSvN19yIA", use_context=True)
	up = Updater("1058922067:AAEWYVrh0RjEHjSDAzZw3tPaTSnvQ40QeCA", use_context=True)
	ud = up.dispatcher
	ud.add_handler(CH("start", mulai))
	ud.add_handler(CH("help", bantuan))
	ud.add_handler(CH("local", local, pass_args=True))
	ud.add_handler(CH("global", ginfo, pass_args=True))
	ud.add_handler(CH("positif", positif, pass_args=True))
	ud.add_handler(CH("meninggal", meninggal, pass_args=True))
	ud.add_handler(CH("cegah", cegah))
	up.start_polling()
#	up.idle()
	return "Status: ON"

if __name__ == "__main__":
	app.run(host="0.0.0.0", port=os.environ.get("PORT"),debug=True)

@app.route('/test', methods=['PUT'])
def create_reading2():
    if not request.json or 'Done' in request.json == True:
        abort(400)
    return jsonify('PUT method is also working', 201)


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


@app.errorhandler(400)
def syntax(error):
    return make_response(
        jsonify({
            'error':
            'The request could not be understood by the server due to malformed syntax.'
        }), 400)


@app.errorhandler(500)
def internal(error):
    return make_response(jsonify({'error': 'Internal Server Error'}), 500)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8001, debug=False)
Exemple #51
0
# POSSIBILITY OF SUCH DAMAGE.
import os
import sys

from flask import Flask, render_template

PROJECT_DIR, PROJECT_MODULE_NAME = os.path.split(
    os.path.dirname(os.path.realpath(__file__)))

FLASK_JSONRPC_PROJECT_DIR = os.path.join(PROJECT_DIR, os.pardir)
if os.path.exists(FLASK_JSONRPC_PROJECT_DIR) \
        and not FLASK_JSONRPC_PROJECT_DIR in sys.path:
    sys.path.append(FLASK_JSONRPC_PROJECT_DIR)

from flask_jsonrpc import JSONRPC

app = Flask(__name__)
app.config.from_object(__name__)
jsonrpc = JSONRPC(app, '/api')


@app.route('/')
def index():
    return render_template('index.html')


import api.hello

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
Exemple #52
0
#!/usr/bin/env python

from flask import Flask
#from flask.ext.triangle import Triangle
from flask_triangle import Triangle

app = Flask(__name__,
            static_url_path="/static",
            static_path="/static",
            static_folder="/static",
            template_folder="/templates")
Triangle(app)

################################################################################
# SERVER STARTUP
################################################################################

if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0')

import scanner.views
Exemple #53
0
'''
Created on 04-Sep-2019

@author: bkadambi
'''

# -*- coding: UTF-8 -*-
"""
hello_flask: First Python-Flask webapp
"""
from flask import Flask  # From module flask import class Flask
app = Flask(__name__)    # Construct an instance of Flask class for our webapp

@app.route('/')   # URL '/' to be handled by main() route handler
def main():
    """Say hello"""
    return 'Hello, world! Welcome to Docker world'

if __name__ == '__main__':  # Script executed directly?
    print("Hello World! Built with a Docker file.")
    app.run(host="0.0.0.0", port=5000, debug=True,use_reloader=True)  # Launch built-in web server and run this Flask webapp
             counter+=1
        conn.commit()
        cursor.close()
        return redirect('/')    
   
@app.route('/delete/<recipe_id>') 
def delete(recipe_id):
    sql = "DELETE FROM recipe WHERE recipe.id =" + recipe_id.format(recipe_id)
    cursor = pymysql.cursors.DictCursor(conn)
    cursor.execute(sql)
    conn.commit()
    return redirect('/')

# do search  
@app.route('/search')
def search():
    if 'search' not in request.args:
        sql = "SELECT * from recipe"
    else:
        search_for = request.args['search']
        sql = """SELECT recipe.date AS date, recipe.intro AS intro, recipe.id AS recipe_id, user.name AS user_name, country.name AS country, recipe.name AS recipe_name, cuisine.name AS cuisine_name FROM user INNER JOIN recipe ON user.id = recipe.user INNER JOIN cuisine ON cuisine.id = recipe.cuisine_id INNER JOIN country ON country.id = user.country WHERE recipe.name LIKE '%""" + search_for + "%'"
    cursor = pymysql.cursors.DictCursor(conn)
    cursor.execute(sql)
    search = cursor.fetchall()
    return render_template('search.html', all_search=search)


if __name__ == '__main__':
    app.run(host=os.environ.get('IP'),
            port=int(os.environ.get('PORT')),
            debug=True)
Exemple #55
0
        if data == [] and reviews == []:
            error = True
            return render_template('index.html',
                                   results=result,
                                   cont=data,
                                   error=error)
        result = True
        return render_template('index.html',
                               results=result,
                               cont=data,
                               error=error)
    else:
        return render_template('index.html',
                               results=result,
                               cont=data,
                               error=error)


@app.route('/api/<string:query>')
def queries(query):

    response, overall_sentiment, data = twitter(query)
    if response == [] and data == []:
        return "Tente outra coisa ;-)"
    keys = response[0].keys()
    return jsonify(sentimento_global=overall_sentiment, response=response)


if __name__ == '__main__':
    app.run(debug=False)
Exemple #56
0
@app.route('/initdb')
def init_page():
    db = DatabaseOperations()
    db.create_tables()
    db.db_init_parameters()
    print("Database initialized and parameters added!")
    return "Database initialized and parameters added!"


@app.route('/excel')
def excel_page():
    excel = ExcelOperations()
    excel.transfer_cloud()
    excel.transfer_storage()
    print("Data was transferred to the database!")
    return "Data was transferred to the database!"


@app.route('/sim')
def simulator_page():
    sim = Simulator()
    sim.sim()
    return "Simulator ended!"


if __name__ == '__main__':
    port = app.config.get("PORT", 5000)
    debug = True
    app.run(host='0.0.0.0', port=port, debug=debug)
Exemple #57
0
                        
                except Exception as res:
                    print("Error")
            thanks = "Terima kasih udah dengerin cerita Meeta! \nEhh!! Ternyata tahap assessment sudah selesai loh!! Yeay \(’-’ )/ \nSekarang, Meeta mau nyariin kamu ahli kesehatan paling bagus yang ada disekitar kamu\n\n\nNanti.. Meeta kabarin ya kalau udah ketemu, sampai nanti."

            return {
                "speech": thanks,
                "displayText": thanks,
                #"data": {},
                #"contextOut": [],
                "source": "line"
            }
        return sendImg(soal)
    
    #jika chat biasa
    else:    
        return {
            "speech": "Masukan kamu salah silahkan kirim lagi",
            "displayText": "Masukan kamu salah silahkan kirim lagi",
            #"data": {},
            #"contextOut": [],
            "source": "line"
        }

if __name__ == '__main__':
    port = int(os.getenv('PORT', 4040))

    print ("Starting app on port %d" %(port))

    app.run(debug=False, port=port, host='0.0.0.0')
Exemple #58
0
    else:
      response = send_email(email=email, data=data, template=template);

    # Check the status code from sendgrid request
    if response.status_code < 400:
      return 'ok', 200
    else:
      return 'Something went wrong, ' + response.status_code
      

@app.route('/schedule', methods=['POST'])
@cross_origin(['Content-Type', 'application/json'])
def schedule_route ():
  if request.method == 'POST': 
    data = request.data
    email, date, data = json.loads(data).values()
    # Check that email and date is provided
    if email is None or date is None:
      return 'Missing email / date', 500
    # Format the provided date to ISO8601
    py_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ').isoformat()
    # Check that the provided date has not already happened
    if py_date < datetime.now().isoformat(): 
      return 'Date has already happened', 500
    # Add send email job to schedule
    scheduler.add_job(send_email, 'date', run_date=py_date, args=[email, data])
    return 'ok', 200

if __name__ == '__main__': 
  app.run(host='0.0.0.0', port=os.getenv('DEFAULT_PORT') or 5000)
Exemple #59
0
#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|.|c|o|m|.|t|w|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Copyright (c) 2014, raspberrypi.com.tw
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Author : sosorry
# Date   : 05/31/2015
# A simple page of flask

from flask import Flask, render_template, Response

app = Flask(__name__)


@app.route("/")
def index():
    return "Hello Flask"


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=True)
Exemple #60
0
        &nbsp&nbsp<a href="/fileupload/">FileUpload</a>
    </body>
</html>
"""


@app.route("/")
def index():
    return render_template_string(index_template)


@app.route("/login/")
def login():
    user = User("testuser")
    login_user(user)
    return redirect("/blog")


@app.route("/logout/")
def logout():
    logout_user()
    return redirect("/")


###############################################################
########################## END BLOG ###########################
###############################################################

if __name__ == '__main__':
    app.run(debug=True, port=8000, use_reloader=True)