当前位置: 首页>>代码示例>>Python>>正文


Python Klein.run方法代码示例

本文整理汇总了Python中klein.Klein.run方法的典型用法代码示例。如果您正苦于以下问题:Python Klein.run方法的具体用法?Python Klein.run怎么用?Python Klein.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在klein.Klein的用法示例。


在下文中一共展示了Klein.run方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_runTCP6

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
 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)
开发者ID:joac,项目名称:klein,代码行数:14,代码来源:test_app.py

示例2: test_runSSL

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
 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)
开发者ID:joac,项目名称:klein,代码行数:17,代码来源:test_app.py

示例3: test_runWithLogFile

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
    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)
开发者ID:pdh,项目名称:klein,代码行数:18,代码来源:test_app.py

示例4: test_run

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
    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)
开发者ID:pdh,项目名称:klein,代码行数:19,代码来源:test_app.py

示例5: one_food

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
                          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)
开发者ID:glasnt,项目名称:klein,代码行数:32,代码来源:html.py

示例6: updates

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
@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 :
开发者ID:digideskio,项目名称:FrameworkBenchmarks,代码行数:32,代码来源:app.py

示例7: login

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
    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)
开发者ID:paulvstheworld,项目名称:hsmail,代码行数:31,代码来源:webmail.py

示例8: abort

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
			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()
开发者ID:faureka,项目名称:scrapy_projects,代码行数:33,代码来源:alibaba_api.py

示例9: Klein

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
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)
开发者ID:notoriousno,项目名称:celery-workshop,代码行数:30,代码来源:Server.py

示例10: turnOnTheLights

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
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)

开发者ID:ynachiket,项目名称:halo,代码行数:30,代码来源:server.py

示例11: list_users

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
@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)
开发者ID:Nobatek,项目名称:umongo,代码行数:32,代码来源:app.py

示例12: shield

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
    '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)
开发者ID:PeterDaveHello,项目名称:pypipins,代码行数:32,代码来源:shields.py

示例13: dict

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
        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'))
开发者ID:wooque,项目名称:bench,代码行数:32,代码来源:bench_klein.py

示例14: str

# 需要导入模块: from klein import Klein [as 别名]
# 或者: from klein.Klein import run [as 别名]
    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>
开发者ID:luhkevin,项目名称:servicesim,代码行数:33,代码来源:simserver.py


注:本文中的klein.Klein.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。