예제 #1
0
def main():
    import meinheld
    import threading
    from multiprocessing import Process

    prepare_static('static/')
    with app.test_request_context():
        initialize()
    port = int(os.environ.get("PORT", '5000'))

    def kill_all():
        for w in workers:
            w.terminate()
    signal.signal(signal.SIGTERM, kill_all)

    def run():
        #meinheld.spawn(subscribe_update)
        th = threading.Thread(target=subscribe_update)
        th.daemon = True
        th.start()
        meinheld.run(app.wsgi_app)

    meinheld.set_backlog(128)
    meinheld.set_keepalive(1)
    meinheld.listen(('0.0.0.0', port))
    meinheld.set_access_logger(None)

    workers = []
    for i in xrange(6):
        w = Process(target=run)
        w.start()
        workers.append(w)
    while True:
        for w in workers:
            w.join(1)
예제 #2
0
파일: app.py 프로젝트: hoyeonbae/popong.com
def main():
    args = cmd_args()
    if args.locale and args.locale != 'auto':
        app.babel.locale_selector_func = lambda: args.locale
    if SERVER_SETTINGS['type']=='flask':
        app.run(SERVER_SETTINGS['host'], SERVER_SETTINGS['port'])
    elif SERVER_SETTINGS['type']=='meinheld':
        print 'On http://%s:%s/' % (SERVER_SETTINGS['host'], SERVER_SETTINGS['port'])
        meinheld.listen((SERVER_SETTINGS['host'], SERVER_SETTINGS['port']))
        meinheld.run(app)
예제 #3
0
def runserver():
    "Runs the App"
    create_app()
    if app.config['MEINHELD']:
        meinheld.listen((app.config['SERVE_HOST'], app.config['SERVE_PORT']))
        meinheld.run(app)
    else:
        app.run(host=app.config['SERVE_HOST'],
                port=app.config['SERVE_PORT'],
                threaded=app.config['THREADED'])
예제 #4
0
def runserver():
    "Runs the App"
    create_app()
    if app.config['MEINHELD']:
        meinheld.listen((app.config['SERVE_HOST'],
                         app.config['SERVE_PORT']))
        meinheld.run(app)
    else:
        app.run(host     = app.config['SERVE_HOST'],
                port     = app.config['SERVE_PORT'],
                threaded = app.config['THREADED'])
예제 #5
0
    def run_server(self):
        """
        run server for api
        """
        if not ENABLE_SERVER:
            logger.info('server not enabled, exit')
            return
        if IS_PROD:
            if APP_PROD_METHOD == APP_PROD_METHOD_GEVENT:
                try:
                    from gevent.pywsgi import WSGIServer
                except ImportError as e:
                    logger.exception(e)
                else:
                    http_server = WSGIServer((API_HOST, API_PORT), app)
                    http_server.serve_forever()

            elif APP_PROD_METHOD == APP_PROD_METHOD_TORNADO:
                try:
                    from tornado.wsgi import WSGIContainer
                    from tornado.httpserver import HTTPServer
                    from tornado.ioloop import IOLoop
                except ImportError as e:
                    logger.exception(e)
                else:
                    http_server = HTTPServer(WSGIContainer(app))
                    http_server.listen(API_PORT)
                    IOLoop.instance().start()

            elif APP_PROD_METHOD == APP_PROD_METHOD_MEINHELD:
                try:
                    import meinheld
                except ImportError as e:
                    logger.exception(e)
                else:
                    meinheld.listen((API_HOST, API_PORT))
                    meinheld.run(app)

            else:
                logger.error("unsupported APP_PROD_METHOD")
                return
        else:
            app.run(host=API_HOST, port=API_PORT, threaded=API_THREADED)
예제 #6
0
    password = request.form.get('password')
    data = query_db("SELECT * from user where username='******' and password='******'".format(username, password))
    if data != []:
        return 'User {0} already exists.'.format(username), 422
    uid = str(uuid4())
    h_password = hashlib.sha512(password).hexdigest()
    bin = {'id': uid,
           'password': h_password,
           'mail': mail
           }
    try:
        data = insert_db("INSERT into user (username, mail, password) VALUES ('{0}', '{1}', '{2}')".format(username, mail, h_password))
    except Exception as e:
        logging.error('failed to put data on db // {0}'.format(e.message))
        return 'KO', 500
    return 'OK', 200


if __name__ == '__main__':
    hostname = socket.gethostname()
    if hostname == 'Stephanes-MacBook-Pro.local':
        print 'DEV ' * 10
        application.debug = True
        application.run(host='0.0.0.0', port=80)

    else:
        print 'PROD ' * 10
        meinheld.listen(("0.0.0.0", 80))
        meinheld.run(application)

예제 #7
0
        self.file = file
        self.buffer_size = buffer_size

    def close(self):
        if hasattr(self.file, 'close'):
            self.file.close()

    def __iter__(self):
        return self

    def next(self):
        data = self.file.read(self.buffer_size)
        if data:
            return data
        raise StopIteration()


def simple_app(environ, start_response):
    status = '200 OK'
    #response_headers = [('Content-type','image/jpeg')]
    response_headers = [('Content-type', 'image/jpeg'),
                        ('Content-Length', '137823')]
    start_response(status, response_headers)
    # use sendfile(2)
    return environ.get('wsgi.file_wrapper',
                       FileWrapper)(open('wallpaper.jpg', 'rb'))


meinheld.listen(("0.0.0.0", 8000))
meinheld.run(simple_app)
예제 #8
0
파일: app.py 프로젝트: Mastermindzh/Subdarr
        log("ERROR: - Download failed.")


def parse_languages(csv_languages):
    """Parse languages string

        Keyword arguments:
        csv_languages -- Comma separated string of languages
    """
    my_languages = []

    for lang in csv_languages.split(","):
        my_languages.append(Language(lang))

    return set(my_languages)


def error(text, error_code):
    """Returns the error in json format

        Keyword arguments:
        text -- Human readable text for the error
        error_code -- http status code
    """
    return '{{"Error": "{}"}}'.format(text), error_code


# finally run the script if file is called directly
meinheld.listen(("0.0.0.0", 5500))
meinheld.run(APP)
예제 #9
0
import meinheld
from flask import jsonify, Flask
from flask_cors import CORS

from handler import fetchNlp

app = Flask(__name__)
CORS(app)

app.add_url_rule('/searchNlp',
                 view_func=fetchNlp.as_view('nlp'))


@app.route('/')
def hello():
    return "MY NLP"


@app.after_request
def apply_caching(response):
    response.headers["Content-Type"] = "application/json"
    return response


if __name__ == '__main__':
    port = 8000
    print('App listening on %s' % str(port))
    meinheld.listen(("0.0.0.0", port))
    meinheld.run(app)
    # app.run( host='0.0.0.0',threaded=True)
예제 #10
0
#!/usr/bin/env python3
"""
A web-based service designed to print labels on your Brother QL label printer.
"""

from app import app, logger
import meinheld

if __name__ == '__main__':
    logger.info("starting labello webserver")
    if app.debug:
        app.run(app.config['host'], app.config['port'])
    else:
        meinheld.listen((app.config['host'], app.config['port']))
        meinheld.run(app)
예제 #11
0
파일: app.py 프로젝트: stevenv17/pruebaTSG
                       tipo='oficina',
                       marca='yy',
                       proveedor='OFF SA',
                       valor_comercial=23000,
                       fecha_compra=datetime(2019, 3, 10),
                       estado='Nuevo')

    responsable1.add_recurso(recurso1)
    responsable2.add_recurso(recurso1)

    responsable4.add_recurso(recurso2)

    responsable3.add_recurso(recurso3)
    responsable1.add_recurso(recurso3)

    try:
        db.session.add_all(
            [responsable1, responsable2, responsable3, responsable4])
        db.session.add_all([recurso1, recurso2, recurso3])
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print('Error:', e)


if __name__ == '__main__':

    pre_run()

    meinheld.listen((HOST, PORT))
    meinheld.run(app)
예제 #12
0
    ret_json = r.json ( )
    return_val = ret_json['return_value']
    return int(return_val)

def setspeed (speed):
    r = requests.post(DEVICE_URL+'/speed',
        data={'access_token':ACCESS_TOKEN, 'args':str(speed)})
    ret_json = r.json ( )
    return_val = ret_json['return_value']
    return int(return_val)

def digitalWrite (pin, state):
    r = requests.post(DEVICE_URL+'/digitalwrite',
        data={'access_token':ACCESS_TOKEN, 'args':pin+','+state})
    ret_json = r.json ( )
    return_val = ret_json['return_value']
    return int(return_val)

def digitalRead (pin):
    r = requests.post(DEVICE_URL+'/digitalread',
        data={'access_token':ACCESS_TOKEN, 'args':pin})
    ret_json = r.json ( )
    return_val = ret_json['return_value']
    return int(return_val)

if __name__ == "__main__" :
   #application.run (host='0.0.0.0', port=8080, debug=False)
   #application.run (host='0.0.0.0')
   meinheld.listen(("0.0.0.0"))
   meinheld.run(app)
예제 #13
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from app import create_app
import meinheld

app = create_app("../config.py")

if __name__ == '__main__':
    meinheld.listen(("0.0.0.0", 9010))
    meinheld.run(app)
예제 #14
0
파일: Sammy.py 프로젝트: Mastermindzh/Sammy
    except Exception:
        route = info

    return run_bash_file(route)



# custom methods
def run_bash_file(filepath):
    """Execute a bash file and returns the output of the command.
    Arguments: Path to the bash file.
    Will return an error if the file doesn't exist.
    """
    if os.path.isfile(filepath):
        process = subprocess.Popen(["bash", filepath], stdout=subprocess.PIPE)
        return process.communicate()[0]
    else:
        return '{"Error":"no such route."}'

def getInfo():
    pwd = subprocess.Popen("pwd", stdout=subprocess.PIPE, )
    dict = {'Host': request.host, 'Working directory': pwd.communicate(0)[0]}
    return dict

@app.route('/shutdownsammy/')
def shutdownSammy():
    meinheld.stop()

meinheld.listen(("0.0.0.0", 5000))
meinheld.run(app)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import meinheld
from izppy.application import setup_app
app = setup_app()
meinheld.listen(('', 8080))
meinheld.run(app)