示例#1
0
文件: test_app.py 项目: joac/klein
 def test_runTCP6(self, reactor, mock_sfs, mock_log, mock_kr):
     """
     L{Klein.run} called with tcp6 endpoint description.
     """
     app = Klein()
     interface = "2001\:0DB8\:f00e\:eb00\:\:1"
     spec = "tcp6:8080:interface={0}".format(interface)
     app.run(endpoint_description=spec)
     reactor.run.assert_called_with()
     mock_sfs.assert_called_with(reactor, spec)
     mock_log.startLogging.assert_called_with(sys.stdout)
     mock_kr.assert_called_with(app)
示例#2
0
文件: test_app.py 项目: joac/klein
 def test_runTCP6(self, reactor, mock_sfs, mock_log, mock_kr):
     """
     L{Klein.run} called with tcp6 endpoint description.
     """
     app = Klein()
     interface = "2001\:0DB8\:f00e\:eb00\:\:1"
     spec = "tcp6:8080:interface={0}".format(interface)
     app.run(endpoint_description=spec)
     reactor.run.assert_called_with()
     mock_sfs.assert_called_with(reactor, spec)
     mock_log.startLogging.assert_called_with(sys.stdout)
     mock_kr.assert_called_with(app)
示例#3
0
文件: test_app.py 项目: joac/klein
 def test_runSSL(self, reactor, mock_sfs, mock_log, mock_kr):
     """
     L{Klein.run} called with SSL endpoint specification.
     """
     app = Klein()
     key = "key.pem"
     cert = "cert.pem"
     dh_params = "dhparam.pem"
     spec_template = "ssl:443:privateKey={0}:certKey={1}"
     spec = spec_template.format(key, cert, dh_params)
     app.run(endpoint_description=spec)
     reactor.run.assert_called_with()
     mock_sfs.assert_called_with(reactor, spec)
     mock_log.startLogging.assert_called_with(sys.stdout)
     mock_kr.assert_called_with(app)
示例#4
0
文件: test_app.py 项目: joac/klein
 def test_runSSL(self, reactor, mock_sfs, mock_log, mock_kr):
     """
     L{Klein.run} called with SSL endpoint specification.
     """
     app = Klein()
     key = "key.pem"
     cert = "cert.pem"
     dh_params = "dhparam.pem"
     spec_template = "ssl:443:privateKey={0}:certKey={1}"
     spec = spec_template.format(key, cert, dh_params)
     app.run(endpoint_description=spec)
     reactor.run.assert_called_with()
     mock_sfs.assert_called_with(reactor, spec)
     mock_log.startLogging.assert_called_with(sys.stdout)
     mock_kr.assert_called_with(app)
示例#5
0
文件: test_app.py 项目: pdh/klein
    def test_runWithLogFile(self, reactor, mock_log, mock_site, mock_kr):
        """
        L{Klein.run} logs to the specified C{logFile}.
        """
        app = Klein()

        logFile = Mock()
        app.run("localhost", 8080, logFile=logFile)

        reactor.listenTCP.assert_called_with(8080, mock_site.return_value, interface="localhost")

        reactor.run.assert_called_with()

        mock_site.assert_called_with(mock_kr.return_value)
        mock_kr.assert_called_with(app)
        mock_log.startLogging.assert_called_with(logFile)
示例#6
0
    def test_runWithLogFile(self, reactor, mock_log, mock_site, mock_kr):
        """
        L{Klein.run} logs to the specified C{logFile}.
        """
        app = Klein()

        logFile = Mock()
        app.run("localhost", 8080, logFile=logFile)

        reactor.listenTCP.assert_called_with(
            8080, mock_site.return_value, interface="localhost")

        reactor.run.assert_called_with()

        mock_site.assert_called_with(mock_kr.return_value)
        mock_kr.assert_called_with(app)
        mock_log.startLogging.assert_called_with(logFile)
示例#7
0
文件: test_app.py 项目: pdh/klein
    def test_run(self, reactor, mock_log, mock_site, mock_kr):
        """
        L{Klein.run} configures a L{KleinResource} and a L{Site}
        listening on the specified interface and port, and logs
        to stdout.
        """
        app = Klein()

        app.run("localhost", 8080)

        reactor.listenTCP.assert_called_with(8080, mock_site.return_value, interface="localhost")

        reactor.run.assert_called_with()

        mock_site.assert_called_with(mock_kr.return_value)
        mock_kr.assert_called_with(app)
        mock_log.startLogging.assert_called_with(sys.stdout)
示例#8
0
    def test_run(self, reactor, mock_log, mock_site, mock_kr):
        """
        L{Klein.run} configures a L{KleinResource} and a L{Site}
        listening on the specified interface and port, and logs
        to stdout.
        """
        app = Klein()

        app.run("localhost", 8080)

        reactor.listenTCP.assert_called_with(
            8080, mock_site.return_value, interface="localhost")

        reactor.run.assert_called_with()

        mock_site.assert_called_with(mock_kr.return_value)
        mock_kr.assert_called_with(app)
        mock_log.startLogging.assert_called_with(sys.stdout)
示例#9
0
def webserver(pq):
    webapp = Klein()

    @webapp.route('/')
    def home(request):
        return 'Hello, World!'

    @webapp.route('/ip/<ip>')
    def getIP(request, ip):
        # We only need ipv4 dotted-quad. Quick regex check, then test the validity of the IP
        if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip):
            try:
                socket.inet_aton(ip)
                pq.put(ip)
                print "ip is: {}".format(ip)
                return "ip is: {}".format(ip)
            except socket.error:
                print "input is not an IP."
                return "This is an IP! Read the RFC 791: https://tools.ietf.org/html/rfc791"
        else:
            print "input is not an IP."
            return "This is not an IP! Read the RFC 791: https://tools.ietf.org/html/rfc791"

    webapp.run(host="0.0.0.0", port=8080)
示例#10
0
        target=kafka_consumer_worker,
        args=(
            t_stop_event,
            bootstrap_servers,
            "heartbeat",
            region,
            __product__,
            threads_mq,
        ),
    )
    threads.append(t_kafka_hb_consumer_worker)

    ###########################################################

    # Starting threads
    for t in threads:
        t.start()

    print("[" + region + "] " + __product__ + " version " + __version__ +
          " (" + env + ') is listening "' + host + ":" + port + '"')

    # Http server
    # log = open('app.log', 'a')
    # if env == 'production':
    #    log = open('/dev/null', 'a')
    # app.run(host, port, log)

    app.run(host, port)

    exit(0)
        Converts audio files to wav files
    """

    print("in ffmpeg")

    args = []

    if codec:
        args += ["-acodec", "pcm_s16le"]
    elif channel:
        args += ["-ac", "1"]
    elif bitrate:
        args += ["-at", "16000"]

    if len(args) == 0:
        return None

    print(f"Running FMPEG with:{args}")

    process = subprocess.run(args=["ffmpeg", "-i", fname] + args + [cvtfname],
                             stdout=PIPE,
                             stderr=PIPE)

    if process.returncode != 0:
        return (False, process.stderr)
    else:
        return (True, process.stdout)


app.run(ADDRESS, PORT)
示例#12
0
def send_now(app_key, request):
    app = Application(key=app_key).auth()

    message = request.args.get('message')[0]
    sound = request.args.get('sound')[0] or 'default'
    badge = request.args.get('badge') or 0
    token = request.args.get('token')[0]
    extra = request.args.get('extra')[0]

    request.setHeader('Content-Type', 'application/json')

    content = dict(alert=message,
                   sound=sound,
                   badge=badge,
                   extra=json.loads(extra))
    if app:
        log.msg('application found: %s' % app.name)
        notification = Notification(token=token, app=app, content=content)
        notification.send()

    else:
        log.msg('No application found with key %s' % app_key[1],
                logLevel=logging.WARNING)

    yield 'OK'


if __name__ == "__main__":
    log.startLogging(sys.stdout)
    app.run("0.0.0.0", 8080)
示例#13
0
@app.route("/updates")
@close_session
def updates(request):
    request.setHeader("Content-Type", "application/json; charset=UTF-8")
    num_queries = getQueryNum(request.args.get("queries")[0])
    worlds = []
    rp = partial(randint, 1, 10000)
    ids = [rp() for _ in xrange(num_queries)]
    ids.sort()
    for id in ids:
        world = db_session.query(World).get(id)
        world.randomNumber = rp()
        worlds.append(world.serialize())
    db_session.commit()
    return json.dumps(worlds)

@app.route("/fortune")
@close_session
def fortune(request):
    request.setHeader("Content-Type", "text/html; charset=UTF-8")
    fortunes = db_session.query(Fortune).all()
    fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
    fortunes.sort(key=attrgetter("message"))
    template = env.get_template("fortunes.html")
    return template.render(fortunes=fortunes)

if __name__ == "__main__":
    app.run("0.0.0.0", 8080)

# vim: set expandtab sw=4 sts=4 ts=4 :
示例#14
0
from klein import Klein
from twisted.internet import defer, reactor

app = Klein()


@app.route('/interrupted')
def interruptRoute(request):
    d = defer.Deferred()
    d.addCallback(_delayedRender)
    reactor.callLater(5, d.callback, request)
    request.notifyFinish().addErrback(_responseFailed, d)
    return d


def _responseFailed(error, call):
    print('Cancelled!')
    call.cancel()


def _delayedRender(request):
    request.write('Sorry for the delay'.encode('utf-8'))


if __name__ == '__main__':
    app.run('localhost', 9000)
示例#15
0
文件: server.py 项目: ynachiket/halo
def turnOnTheLights(states, timeoutFlag = False):
    for pixel in xrange(len(states)):
        current_state = states[pixel]
        if current_state.lower() == 'ok':
            ok(pixel, timeoutFlag)
        elif current_state.lower() == 'warning':
            warning(pixel, timeoutFlag)
        elif current_state.lower() == 'critical':
            critical(pixel, timeoutFlag)
        else:
            unknown(pixel) 
   
def init():
    global states
    global leds
    global timeout
    number_of_lights = 32
    timeout = reactor.callLater(SHIFTTIME,shiftOne)

    states = deque(['unknown']*number_of_lights)

    spidev = file("/dev/spidev0.0", "wb")
    leds = ledstrip.LEDStrip(pixels=number_of_lights, spi=spidev)

if __name__ == "__main__":
    #app.config['DEBUG'] = True
    init()
    app.run(host='::', port=5000)

示例#16
0
resource = app.resource
mode = release

https = False

for v in sys.argv:
    if v.lower() == "test":
        mode = test
    if v.lower() == "debug":
        mode = debug
    if v.lower() == 'https':
        https = True

endpointdesc = 'ssl:8084:privateKey=' + privateKeyPath + ':certKey=' + certificatePath
if not https:
    endpointdesc = ''

if mode == test:
    print("Testing mode, no server running.")
    print("to start server: app.run(<local/0.0.0.0>',<port>)")
##local test
elif mode == debug:
    print("Running on localhost")
    app.run('localhost', 8084, endpoint_description=endpointdesc)
##release
elif mode == release:
    print("Running on 0.0.0.0")
    app.run('0.0.0.0', 8084, endpoint_description=endpointdesc)


示例#17
0
        return dfd

    def item_scraped(self, item, response, spider):
        self.items.append(item)

    def return_items(self, result):
        return self.items

def return_spider_output(output):
    """
    :param output: items scraped by CrawlerRunner
    :return: json with list of items
    """
    # this just turns items into dictionaries
    # you may want to use Scrapy JSON serializer here
    return json.dumps([dict(item) for item in output])

@application.route("/api")
def schedule(request):
    settings = get_project_settings()
    runner = MyCrawlerRunner(settings)
    deferred = runner.crawl(CovidSpider)
    deferred.addCallback(return_spider_output)
    return deferred


application.run("localhost", 8080)



示例#18
0
        d = xmltodict.parse(content)
        if 'offers' in d:
            return read_ceneo_v2(d)
        else:
            return read_google_shopping(d)
    elif url.endswith('.csv'):
        return read_csv(content, delim=',')
    else:
        return read_csv(content, delim='\t')


@defer.inlineCallbacks
def return_info(response):
    text = yield response.content()
    v = read_any_feed(text, response.request.absoluteURI.decode('utf-8'))
    return json.dumps(v)


@app.route("/read", methods=['POST'])
def get_category(request):
    content = json.loads(request.content.read())
    url = content['url']
    d = treq.get(url)
    d.addCallback(return_info)
    return d


resource = app.resource

app.run("0.0.0.0", 5007)
示例#19
0
    'd': DownloadHandler,
    'download': DownloadHandler,
    'v': VersionHandler,
    'version': VersionHandler,
    'wheel': WheelHandler,
    'egg': EggHandler,
    'license': LicenseHandler,
    'format': FormatHandler,
    'py_versions': PythonVersionsHandler,
    'implementation': ImplementationHandler,
    'status': StatusHandler,
}


@app.route('/<string:generator>/<string:package>/badge.<string:extension>')
def shield(request, generator, package, extension):
    gc.collect()
    ext = mimetypes.types_map[".{0}".format(extension)]
    request.headers.update({'content-type': ext})
    klass = generators[generator]()
    img = klass.get(request, package, extension)
    return img


if __name__ == '__main__':
    if not os.path.exists(FILE_CACHE):
        os.mkdir(FILE_CACHE)
    if '.svg' not in mimetypes.types_map:
        mimetypes.add_type("image/svg+xml", ".svg")
    app.run("localhost", 8888)
    request.setHeader('Access-Control-Allow-Headers', 'x-prototype-version,x-requested-with')
    request.setHeader('Access-Control-Max-Age', 2520)
    
    content = json.loads(request.content.read().decode("utf8"))
    print(content)
    command = content['command']
    DID = content['deviceID']

    if DID != "00000000":
        toSend={"CMD":"HMOD","MODE":command, "TS": str(int(time.time()))}
        remote_device = RemoteXBeeDevice(device, XBee64BitAddress.from_hex_string(DID))

        # Send data using the remote object.
        device.send_data_async(remote_device, json.dumps(toSend))
    else:
        toSend={"CMD":"HMOD","MODE":command, "TS": str(int(time.time()))}
        print("broadcasting command " + json.dumps(toSend))
        device.send_data_broadcast(json.dumps(toSend))




    return json.dumps({"result":"success"})


device = DigiMeshDevice(PORT, BAUD_RATE)
device.open()
device.add_data_received_callback(my_data_received_callback)

app.run("0.0.0.0", 5001)
示例#21
0
    for ch0, ch2 in zip(text0, Y_pred_text):
        ch = ch0
        if ch0.lower() != ch2.lower() and ch2 != " ":
            ch = "<span class='mod'>" + ch2 + "</span>"
        rez.append(ch)
    rez_str = "".join(rez).strip()
    return rez_str


#DBG()

app = Klein()


@app.route("/ajax")
def generate_ajax(request):
    txt = request.content.read().decode("utf-8")
    print("GOT TXT=", txt, type(txt))
    request.setHeader('Content-Type', 'text/html; charset=utf-8')
    request.write(predict(model, txt).encode("utf-8"))


@app.route("/", branch=True)
def generate_index(request):
    return File("./app")


if __name__ == '__main__':
    print " * Web API started"
    app.run(host='0.0.0.0', port=5080)
示例#22
0
    elif edit_permission is LOCKED_EDITS:
        return perform_locked_edit(article_id, request)

    else:
        request.setResponseCode(400)
        return "ERROR: Article requested for edit is in an invalid state. Contact the administrator if this error message persists."


# Again, apologies for the abysmal security, but due to time constrains this was necessary - in the real world this would either be a proper user/pass auth schema, OAuth2, or a specialty api key
@app.route(
    '/change_article_permissions/<article_id>/<permission>/<username>/<password>'
)
def change_article_permissions(request, article_id, permission, username,
                               password):
    """ This endpoint allows qualified users to change the editing permissions of an article """

    print article_id, permission, username, password

    if not validate_user(username, password):
        request.setResponseCode(401)
        return "User is not authorized to access the requested resource."

    return "Article Permissions updated" if update_article_permissions(
        article_id,
        permission) else "There was a problem updating the permissions"


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8888)
示例#23
0

if __name__ == '__main__':
    args = parser.parse_args()  # Command line arguments.

    # Tell Twisted how to serve websockets:
    factory = WebSocketServerFactory(
        f'ws://{args.interface}:{args.websocket_port}'
    )

    # Set up the default name from the command line.
    factory.default_name = args.default_name
    names.add(factory.default_name)

    # factory.protocol will be returned by factory.buildProtocol.
    # This is a shortcut instead of subclassing WebSocketServerFactory and
    # defining our own buildProtocol method.
    # If you wanted to disallow connections from certain hosts then you could
    # subclass WebSocketServerFactory and create your own buildProtocol method
    # that returned None when the hostname was blacklisted.
    factory.protocol = WebSocketProtocol

    # Create kwargs for use with the index method. By doing things this way we
    # don't hard code anything in javascript.
    index_kwargs.update(
        hostname=getfqdn(), http_port=args.http_port,
        websocket_port=args.websocket_port
    )
    listenWS(factory, interface=args.interface)  # Listen for websockets.
    app.run(host=args.interface, port=args.http_port)  # Main loop.
示例#24
0
    d.addCallback(mainpage)
    return d


@app.route('/login', methods=['GET', 'POST'])
def login(request):

    if request.method == 'POST':
        qs_dict = getFieldDict(request)

        email = qs_dict['email']
        password = qs_dict['password']
        session = request.getSession()

        login = ILogin(session)
        login.email = email
        login.password = password

        return request.redirect('/')

    return render_template('login.html')



@app.route('/success')
def success(request):
    return 'Your message was sent!!!!!!!!!!!!!!!!!!'

app.run('localhost', 8080)
示例#25
0
from klein import Klein
from twisted.internet import task, reactor
from twisted.web.resource import Resource

import Sequential

app = Klein()

def delayedCall(n):
    return 'Delayed for %d seconds' % n

@app.route('/delay/<int:t>')
def delay(requests, t):
    """
    Delay the response by t seconds
    """
    if t > 0:
        d = task.deferLater(reactor, t, delayedCall, t)
        return d
    else:
        return delayedCall(0)

@app.route('/upload', branch=True)
def sequential(request):
    return Sequential.app.resource()


app.run('localhost', 8000)
示例#26
0
    returnValue(
        jsonify(
            request, {
                '_total': (yield User.count()),
                '_page': page,
                '_per_page': 10,
                '_items': [dump_user_no_pass(u) for u in users]
            }))


@app.route('/users', methods=['POST'])
@locale_from_request
@inlineCallbacks
def create_user(request):
    payload = get_json(request)
    if payload is None:
        raise Error(
            400,
            'Request body must be json with Content-type: application/json')
    try:
        user = User(**payload)
        yield user.commit()
    except ValidationError as ve:
        raise Error(400, jsonify(request, message=ve.args[0]))
    returnValue(jsonify(request, dump_user_no_pass(user)))


if __name__ == '__main__':
    reactor.callWhenRunning(populate_db)
    app.run('localhost', 5000)
示例#27
0
    """
    Base endpoint to get current counter value
    :param request:
    :return: JSON representation of response
    """
    return json.dumps({"counter": int(storage.read())})


@app.route('/increment', methods=['POST'])
def increment(request):
    """
    Endpoint to increment the counter
    :param request:
    :return: JSON representation of response
    """
    return json.dumps({"counter": int(storage.incr())})


@app.route('/increment', methods=['DELETE'])
def reset(request):
    """
    Endpoint to reset the counter
    :param request:
    :return: JSON representation of response
    """
    return json.dumps({"counter": int(storage.reset())})


if __name__ == "__main__":
    app.run(settings.SERVER_HOST, settings.SERVER_PORT)
示例#28
0
"""
How to test using curl:

?> curl localhost:9000/branch/hello
?> curl localhost:9000/branch/blue/first
?> curl localhost:9000/branch/blue/second
?> curl localhost:9000/branch/blue/third
"""

from klein import Klein
from twisted.web.static import File

import blueprints

app = Klein()


@app.route('/branch', branch=True)
def branchOff(request):
    return blueprints.app.resource(
    )  # get the Resource object from the Klein app in the blueprints module


if __name__ == '__main__':
    app.run(host='localhost', port=9000)
示例#29
0
from klein import Klein
app = Klein()


@app.route('/')
def pg_root(request):
    return 'I am the root2 page!'


@app.route('/about2')
def pg_about(request):
    return 'I am a Klein application2!'


app.run("localhost", 8089)
示例#30
0
class Reflector:
    '''
    main class that does all the work
    '''
    def __init__(self, args, config):
        self.args = args
        self.config = config
        self.http_server = Klein()
        self.handler_threads = []
        self.server_threads = []
        self._log('Instantiated class Reflector', 'info')

        # simple healthcheck URI to check if the app is up
        @self.http_server.route('/__hc', methods=['GET'])
        def healthcheck(request):
            return str(200)

        @self.http_server.route('/')
        @self.http_server.route('/<uri>')
        def handle_get(request):
            '''
            handle incoming requests
            '''
            tpool = []
            for s in range(0, len(self.config['upstream'])):
                tpool.append(
                    self._spawn(target=self._http_redirect,
                                req=request,
                                thread_list=self.handler_threads,
                                index=s))
            for t in tpool:
                t.join()
            return str(request.content.read())

    # private methods
    def _log(self, msg, level='info'):
        '''
        logging function, writes to stdout
        '''
        out = {
            'timestamp': str(datetime.now()),
            'level': level.upper(),
            'message': str(msg)
        }
        if self.args.debug:
            print json.dumps(out)

    def _spawn(self, **kwargs):
        '''
        spawn threads
        '''
        if 'req' in kwargs:
            t = Thread(target=kwargs['target'],
                       args=(kwargs['index'], kwargs['req']))
        else:
            t = Thread(target=kwargs['target'])
        t.start()
        return t

    def _http_redirect(self, index, req):
        '''forward http to upstream'''
        if '?' in req.uri:
            params == True
            params = req.uri.split('?')[1]
        else:
            params = ''
        if self.config['upstream'][index]['uri']:
            if params == True:
                url = 'http://{}:{}{}?{}'.format(
                    self.config['upstream'][index]['host'],
                    self.config['upstream'][index]['port'],
                    self.config['upstream'][index]['uri'] + req.uri, params)
            else:
                url = 'http://{}:{}{}'.format(
                    self.config['upstream'][index]['host'],
                    self.config['upstream'][index]['port'],
                    self.config['upstream'][index]['uri'] + req.uri)
        else:
            url = 'http://{}:{}{}'.format(
                self.config['upstream'][index]['host'],
                self.config['upstream'][index]['port'], req.uri)
        headers = req.getAllHeaders()
        body = req.content
        if req.method.lower() in ['get', 'options']:
            r = requests.get(url, headers=headers, timeout=5)
        elif req.method.lower() in ['post', 'put', 'delete']:
            r = requests.post(url, headers=headers, data=body, timeout=5)

    # public methods
    def start(self):
        '''
        start listening for connections
        '''
        self._log('Starting Reflector')
        self.http_server.run(self.args.host, self.args.port)
        return
示例#31
0
                return path, expire
    raise Fail('uuid not found')


app = Klein()

with app.subroute(BASEURL) as app:

    @app.route('/<uuid>/<filename>', methods=['GET', 'HEAD'])
    def serve_files(request, uuid, filename):
        UUID(uuid)  # just create it to see if it validates
        path, expiry_date = get_file_info(uuid)
        if datetime.now(timezone.utc) > expiry_date: raise Fail('expired')
        if filename != os.path.basename(path):
            raise Fail('path does not match')
        return File(os.path.join(BASEDIR, path))

    @app.route('/<uuid>/<filename>/', methods=['GET', 'HEAD'], branch=True)
    def serve_dir(request, uuid, filename):
        return serve_files(request, uuid, filename)

    @app.handle_errors
    def handle_errors(request, failure):
        print('Fail:', failure.getErrorMessage())
        #failure.printBriefTraceback()
        return File.childNotFound


if __name__ == '__main__':
    app.run("localhost", PORT)
示例#32
0
    'd': DownloadHandler,
    'download': DownloadHandler,
    'v': VersionHandler,
    'version': VersionHandler,
    'wheel': WheelHandler,
    'egg': EggHandler,
    'license': LicenseHandler,
    'format': FormatHandler,
    'py_versions': PythonVersionsHandler,
    'implementation': ImplementationHandler,
    'status': StatusHandler,
}


@app.route('/<string:generator>/<string:package>/badge.<string:extension>')
def shield(request, generator, package, extension):
    gc.collect()
    ext = mimetypes.types_map[".{0}".format(extension)]
    request.headers.update({'content-type': ext})
    klass = generators[generator]()
    img = klass.get(request, package, extension)
    return img


if __name__ == '__main__':
    if not os.path.exists(FILE_CACHE):
        os.mkdir(FILE_CACHE)
    if '.svg' not in mimetypes.types_map:
        mimetypes.add_type("image/svg+xml", ".svg")
    app.run("localhost", 8888)
示例#33
0
        result = yield db.runQuery("SELECT title, thumb, nc, nv FROM tst ORDER BY id DESC LIMIT 10")
        data = result and [dict(title=r[0], thumb=r[1], nc=r[2], nv=r[3]) for r in result] or None
        resp = dict(list=data)

    elif coin < 8:
        title = randstr(140)
        thumb = randstr(140)
        nc = randint(0, 1000)
        nv = randint(0, 5000)
        yield db.runOperation("INSERT INTO tst(title, thumb, nc, nv) VALUES (%s, %s, %s, %s)",
                              (title, thumb, nc, nv,))
        resp = dict(action="insert", title=title, thumb=thumb, nc=nc, nv=nv)

    else:
        title = randstr(140)
        thumb = randstr(140)
        nc = randint(0, 1000)
        nv = randint(0, 5000)
        yield db.runOperation("UPDATE tst SET title=%s, thumb=%s, nc=%s, nv=%s "
                              "WHERE id=(SELECT max(id) as m FROM tst LIMIT 1)",
                              (title, thumb, nc, nv,))
        resp = dict(action="update", title=title, thumb=thumb, nc=nc, nv=nv)
    
    request.setHeader('Content-Type', 'application/json')
    returnValue(json.dumps(resp))

resource = app.resource

if __name__ == "__main__":
    app.run("localhost", 8080, logFile=open('/dev/null'))
示例#34
0
文件: html.py 项目: glasnt/klein
                          tags.td(slot("rating"), " stars")),
                  tags.tr(tags.td("Carbs:"),
                          tags.td(slot("carbohydrates")))))
def one_food(request, food):
    random = random_from_string(food)
    return {"name": food,
            "pageTitle": "Food: {}".format(food),
            "rating": random.randint(1, 5),
            "carbohydrates": random.randint(0, 100)}

@myStyle.routed(
    app.route("/places/<place>"),
    tags.div(style="color: green")(
        tags.h1("Place: ", slot("name")),
        tags.div(slot("latitude"), "° ", slot("longitude"), "°"),
        tags.div(tags.h2("Foods Found Here:"),
                 tags.ul(tags.li(render="foods:list")(
                     tags.a(href=["/foods/", slot("item")])(slot("item")))))))
def one_place(request, place):
    random = random_from_string(place)
    possible_foods = ["hamburgers", "cheeseburgers", "hot dogs", "pizza",
                      "叉烧", "皮蛋", "foie gras"]
    random.shuffle(possible_foods)
    return {"name": place,
            "pageTitle": "Place: {}".format(place),
            "latitude": random.uniform(-90, 90),
            "longitude": random.uniform(-180, 180),
            "foods": possible_foods[:3]}

app.run("localhost", 8080)
示例#35
0
#PYTHONPATH=/Users/Standard/Documents/gitsrc/Python/Useful/HTTP twistd -n web --class=simple_server.resource
# or
#./exc.sh simepl_server            (or whatever you decide to name this file)
#
# I don't know why it's so complicated to run...
# I think it has to do with the fact that I'm running a twisted server and klein is an extension of twisted

from klein import Klein

app = Klein()


@app.route('/')
def home(request):
    return "Welcome!"


@app.route('/<Id>')
def print_id(request, Id):
    return Id


app.run("localhost", 8081)
示例#36
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from klein import run, route
from twisted.web.template import tags, slot
from klein import Klein, Plating

from input_handler import handle_input

app = Klein()

myStyle = Plating(
    tags=tags.html(
        tags.head(tags.title(slot("pageTitle"))),
        tags.body(tags.h1(slot("pageTitle"), Class="titleHeading"),
                  tags.div(slot(Plating.CONTENT)))
    )
)

@myStyle.routed(
    app.route("/input/"),
    tags.div())
def input(request):
	return {"r":['Hello, world!']}



if __name__ == '__main__':
	app.run("localhost", 8080)
    
示例#37
0
from twisted.web.static import File
from klein import Klein
import time

app = Klein()


@app.route('/hello')
def hello(request):
    time.sleep(2)
    return File('./templates/hello.html')

if __name__ == '__main__':
    app.run('localhost', 9090)
import json
import codecs
from tflearn.data_utils import to_categorical, pad_sequences
from klein import Klein
import predict
import train

app = Klein()


@app.route('/api/ai/getSentimentPrediction/<comment>', methods=['GET'])
def prediction(request, comment):
    #    comment = request.args.get('comment', )[0]
    prediction = predict.prediction_module(comment)
    return prediction


@app.route('/api/ai/trainAIEngine', methods=['GET'])
def training(request):
    training = train.training_module()
    return training


@app.route('/api/ai/getSentimentSummary', methods=['GET'])
def summary(request):
    summary = predict.prediction_summary()
    return summary


app.run("localhost", 9080)
示例#39
0
文件: app.py 项目: Nobatek/umongo
@inlineCallbacks
def list_users(request):
    page = int(request.args.get('page', 1))
    users = yield User.find(limit=10, skip=(page - 1) * 10)
    returnValue(jsonify(request, {
        '_total': (yield User.count()),
        '_page': page,
        '_per_page': 10,
        '_items': [dump_user_no_pass(u) for u in users]
    }))


@app.route('/users', methods=['POST'])
@locale_from_request
@inlineCallbacks
def create_user(request):
    payload = get_json(request)
    if payload is None:
        raise Error(400, 'Request body must be json with Content-type: application/json')
    try:
        user = User(**payload)
        yield user.commit()
    except ValidationError as ve:
        raise Error(400, jsonify(request, message=ve.args[0]))
    returnValue(jsonify(request, dump_user_no_pass(user)))


if __name__ == '__main__':
    reactor.callWhenRunning(populate_db)
    app.run('localhost', 5000)
示例#40
0
def main():
    parser = argparse.ArgumentParser()

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-m", "--mainnet", action="store_true", default=False,
                       help="Use MainNet instead of the default TestNet")
    group.add_argument("-t", "--testnet", action="store_true", default=False,
                       help="Use TestNett instead of the default TestNet")
    group.add_argument("-p", "--privnet", action="store_true", default=False,
                       help="Use PrivNet instead of the default TestNet")
    group.add_argument("--coznet", action="store_true", default=False,
                       help="Use the CoZ network instead of the default TestNet")
    group.add_argument("-c", "--config", action="store", help="Use a specific config file")

    parser.add_argument("--port-rpc", type=int, help="port to use for the json-rpc api (eg. 10332)")
    parser.add_argument("--port-rest", type=int, help="port to use for the rest api (eg. 80)")

    args = parser.parse_args()

    if not args.port_rpc and not args.port_rest:
        print("Error: specify at least one of --port-rpc / --port-rest")
        parser.print_help()
        return

    if args.port_rpc == args.port_rest:
        print("Error: --port-rpc and --port-rest cannot be the same")
        parser.print_help()
        return

    # Setup depending on command line arguments. By default, the testnet settings are already loaded.
    if args.config:
        settings.setup(args.config)
    elif args.mainnet:
        settings.setup_mainnet()
    elif args.testnet:
        settings.setup_testnet()
    elif args.privnet:
        settings.setup_privnet()
    elif args.coznet:
        settings.setup_coznet()

    # Write a PID file to easily quit the service
    write_pid_file()

    # Instantiate the blockchain and subscribe to notifications
    blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
    Blockchain.RegisterBlockchain(blockchain)
    dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks)
    dbloop.start(.1)

    # Disable logging smart contract events
    settings.set_log_smart_contract_events(False)

    # Start the notification db instance
    ndb = NotificationDB.instance()
    ndb.start()

    # Start a thread with custom code
    d = threading.Thread(target=custom_background_code)
    d.setDaemon(True)  # daemonizing the thread will kill it when the main thread is quit
    d.start()

    # Run
    reactor.suggestThreadPoolSize(15)
    NodeLeader.Instance().Start()

    host = "0.0.0.0"

    if args.port_rpc:
        logger.info("Starting json-rpc api server on http://%s:%s" % (host, args.port_rpc))
        api_server_rpc = JsonRpcApi(args.port_rpc)
        endpoint_rpc = "tcp:port={0}:interface={1}".format(args.port_rpc, host)
        endpoints.serverFromString(reactor, endpoint_rpc).listen(Site(api_server_rpc.app.resource()))

    if args.port_rest:
        logger.info("Starting notification api server on http://%s:%s" % (host, args.port_rest))
        api_server_rest = NotificationRestApi()
        endpoint_rest = "tcp:port={0}:interface={1}".format(args.port_rest, host)
        endpoints.serverFromString(reactor, endpoint_rest).listen(Site(api_server_rest.app.resource()))

    app = Klein()
    app.run(host, 9999)
示例#41
0
            if price is not None:
                product['offers'] = [price]

        return product
    except Exception as e:
        print(e)

    return {}


@defer.inlineCallbacks
def return_info(response):
    text = yield response.content()
    url = response.request.absoluteURI.decode("utf-8")
    v = get_products_details(text, url)  #response.request.absoluteURI)
    return json.dumps(v)


@app.route("/parse", methods=['POST'])
def get_category(request):
    content = json.loads(request.content.read())
    url = content['url']
    d = treq.get(url)
    d.addCallback(return_info)
    return d


resource = app.resource

app.run("0.0.0.0", 5005)
示例#42
0
			log.msg(e,logLevel=logging.DEBUG)
			# response.close()
			# abort(404)
			pass

		# print response2.status_code
		try:
			content = yield response.content()
			soup = BeautifulSoup(content,"html.parser")
			details = soup.find_all("table",{"class":"table"})
			basic_details = details[0].find_all("tr")
			personl_details = details[1].find_all("tr")
			outdict = {}
			for idx,lines in enumerate(basic_details):
				outdict[clean_text(lines,'th')] = clean_text(lines,'td')
				# print clean_text(lines,'td')
			for lines in personl_details:
				outdict[clean_text(lines,'th')] = clean_text(lines,'td')
			returnValue(json.dumps(outdict))
		except KeyError:
				# abort(400)
				pass
	




if __name__ == '__main__':
	app.run(host='localhost',port=5000)
	observer = log.PythonLoggingObserver()
	observer.start()
示例#43
0
    parser.add_argument('-p', '--port', nargs='?', help="Specify the port the node will listen on")

    parser.add_argument('-c', '--config', default='', help="The config file. Only for the controller node")
    parser.add_argument('-i', '--inventory', default='', help="The inventory file")
    parser.add_argument('-f', '--function', default='regular', help="The function of the node")

    args = parser.parse_args()

    address = str(args.address)
    port = int(args.port)
    config = args.config
    inventory = args.inventory
    function = args.function

    node = Simnode(args.nodetype, config, inventory)
    app.run(address, port)

'''
routes:
/<node-id>
/<node-id>/status/<http status code>
/<node-id>/latency</latency>
/<node-id>/info

/<node-id>/text/<text payload>
/<node-id>/file/<absolute or relative file payload> ... We should also be able to POST files to a certain location on the filesystem and retrieve that file with GET
/<node-id>/method/<custom simnode method to call>/<csv-separated args>

NOTE: Should probably set limits on these...cpu, mem, I/O, and disk space to 75% max
/<node-id>/cpu/<cpu percentage> ... can probably use this: http://people.seas.harvard.edu/~apw/stress/
/<node-id>/mem/<memory percentage>