• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python website.Website类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中aspen.website.Website的典型用法代码示例。如果您正苦于以下问题:Python Website类的具体用法?Python Website怎么用?Python Website使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: main

def main(argv=None):
    """http://aspen.io/cli/
    """
    try:

        # Do imports.
        # ===========
        # These are in here so that if you Ctrl-C during an import, the
        # KeyboardInterrupt is caught and ignored. Yes, that's how much I care.
        # No, I don't care enough to put aspen/__init__.py in here too.

        import os
        import logging
        import socket
        import sys
        import time
        import traceback
        from os.path import exists, join

        from aspen.server import restarter
        from aspen.website import Website

        log = logging.getLogger("aspen.cli")

        # Actual stuff.
        # =============

        if argv is None:
            argv = sys.argv[1:]
        website = Website(argv)
        try:
            if hasattr(socket, "AF_UNIX"):
                if website.sockfam == socket.AF_UNIX:
                    if exists(website.address):
                        log.info("Removing stale socket.")
                        os.remove(website.address)
            if website.port is not None:
                welcome = "port %d" % website.port
            else:
                welcome = website.address
            log.info("Starting %s engine." % website.engine.name)
            website.engine.bind()
            log.warn("Greetings, program! Welcome to %s." % welcome)
            if website.changes_kill:
                log.info("Aspen will die when files change.")
                restarter.install(website)
            website.start()
        except KeyboardInterrupt, SystemExit:
            pass
        except:
            traceback.print_exc()
        finally:
            if hasattr(socket, "AF_UNIX"):
                if website.sockfam == socket.AF_UNIX:
                    if exists(website.address):
                        os.remove(website.address)
            website.stop()
开发者ID:falstaff84,项目名称:aspen,代码行数:57,代码来源:__init__.py


示例2: test_github_oauth_url_not_susceptible_to_injection_attack

 def test_github_oauth_url_not_susceptible_to_injection_attack(self):
     expected = 'https://github.com/login/oauth/authorize?client_id=cheese&redirect_uri=nuts?data=b3B0LWluLC9vbi90d2l0dGVyLyI+PGltZyBzcmM9eCBvbmVycm9yPXByb21wdCgxKTs+Lw=='
     website = Website([])
     website.github_client_id = 'cheese'
     website.github_callback= 'nuts'
     actual = github.oauth_url( website=website
                              , action='opt-in'
                              , then=self.xss
                               )
     assert actual == expected, actual
开发者ID:angleman,项目名称:www.gittip.com,代码行数:10,代码来源:test_elsewhere.py


示例3: __call__

    def __call__(self, path='/', *a):
        """Given an URL path, return 

        This only allows you to simulate GET requests with no querystring, so
        it's limited. But it's a something. Kind of. Almost.

        """
        website = Website(self.argv + list(a))
        request = StubRequest(path)
        request.website = website
        response = website.handle(request)
        return response
开发者ID:jarpineh,项目名称:aspen,代码行数:12,代码来源:__init__.py


示例4: __call__

    def __call__(self, path='/', *a):
        """Given an URL path, return

        This only allows you to simulate GET requests with no querystring, so
        it's limited. But it's a something. Kind of. Almost.

        """
        path = path.encode('ascii') # StubRequest/Request takes bytestings only.
        website = Website(self.argv + list(a))
        request = StubRequest(path)
        request.website = website
        response = website.handle_safely(request)
        return response
开发者ID:prodigeni,项目名称:aspen-python,代码行数:13,代码来源:__init__.py


示例5: test_call_wraps_wsgi_middleware

def test_call_wraps_wsgi_middleware():
    website = Website([])
    website.wsgi_app = TestMiddleware(website.wsgi_app)
    respond = [False, False]
    def start_response_should_404(status, headers):
        assert status.lower().strip() == '404 not found', status
        respond[0] = True
    website(build_environ('/'), start_response_should_404)
    assert respond[0]
    def start_response_should_200(status, headers):
        assert status.lower().strip() == '200 ok', status
        respond[1] = True
    website(build_environ('/middleware'), start_response_should_200)
    assert respond[1]
开发者ID:Web5design,项目名称:aspen-python,代码行数:14,代码来源:test_website.py


示例6: test_configuration_script_can_set_renderer_default

def test_configuration_script_can_set_renderer_default():
    CONFIG = """
website.renderer_default="stdlib_format"
    """
    SIMPLATE = """
name="program"
[----]
Greetings, {name}!
    """
    mk(
       ('.aspen/configure-aspen.py', CONFIG),
       ('index.html.spt', SIMPLATE)
      )
    w = Website(['--www_root', FSFIX, '-p', fix('.aspen'), '--show_tracebacks=yes'])
    request = StubRequest(b'/')
    request.website = w
    response = w.handle_safely(request)
    actual = response.body.strip()
    expected = 'Greetings, program!'
    assert actual == expected, actual
开发者ID:ArmstrongJ,项目名称:aspen-python,代码行数:20,代码来源:test_configuration.py


示例7: test_double_failure_still_sets_response_dot_request

def test_double_failure_still_sets_response_dot_request():
    mk( '.aspen'
      , ('.aspen/foo.py', """
def bar(response):
    response.request
""")
      , ( '.aspen/configure-aspen.py'
        , 'import foo\nwebsite.hooks.outbound.append(foo.bar)'
         )
      , ('index.html.spt', "raise heck\n[---]\n")
       )

    # Intentionally break the website object so as to trigger a double failure.
    project_root = os.path.join(FSFIX, '.aspen')
    website = Website(['--www_root='+FSFIX, '--project_root='+project_root])
    del website.renderer_factories

    response = website.handle_safely(StubRequest())

    expected = 500
    actual = response.code
    assert actual == expected, actual
开发者ID:Web5design,项目名称:aspen-python,代码行数:22,代码来源:test_website.py


示例8: _main

def _main(argv):

    # Do imports.
    # ===========
    # These are in here so that if you Ctrl-C during an import, the
    # KeyboardInterrupt is caught and ignored. Yes, that's how much I care.
    # No, I don't care enough to put aspen/__init__.py in here too.

    import os
    import signal
    import socket
    import sys
    import traceback

    import aspen
    from aspen import execution
    from aspen.website import Website


    # Set up signal handling.
    # =======================

    def SIGHUP(signum, frame):
        aspen.log_dammit("Received HUP, re-executing.")
        execution.execute()
    if not aspen.WINDOWS:
        signal.signal(signal.SIGHUP, SIGHUP)

    def SIGINT(signum, frame):
        aspen.log_dammit("Received INT, exiting.")
        raise SystemExit
    signal.signal(signal.SIGINT, SIGINT)


    def SIGQUIT(signum, frame):
        aspen.log_dammit("Received QUIT, exiting.")
        raise SystemExit
    if not aspen.WINDOWS:
        signal.signal(signal.SIGQUIT, SIGQUIT)


    # Website
    # =======
    # User-developers get this website object inside of their resources and
    # hooks. It provides access to configuration information in addition to
    # being a WSGI callable and holding the request/response handling
    # logic. See aspen/website.py

    if argv is None:
        argv = sys.argv[1:]
    website = Website(argv)


    # Start serving the website.
    # ==========================
    # This amounts to binding the requested socket, with logging and
    # restarting as needed. Wrap the whole thing in a try/except to
    # do some cleanup on shutdown.

    try:
        if hasattr(socket, 'AF_UNIX'):
            if website.network_sockfam == socket.AF_UNIX:
                if os.path.exists(website.network_address):
                    aspen.log("Removing stale socket.")
                    os.remove(website.network_address)
        if website.network_port is not None:
            welcome = "port %d" % website.network_port
        else:
            welcome = website.network_address
        aspen.log("Starting %s engine." % website.network_engine.name)
        website.network_engine.bind()
        aspen.log_dammit("Greetings, program! Welcome to %s." % welcome)
        if website.changes_reload:
            aspen.log("Aspen will restart when configuration scripts or "
                      "Python modules change.")
            execution.install(website)
        website.start()

    except socket.error:

        # Be friendly about port conflicts.
        # =================================

        # The traceback one gets from a port conflict or permission error
        # is not that friendly. Here's a helper to let the user know (in
        # color?!) that a port conflict or a permission error is probably
        # the problem. But in case it isn't (website.start fires the start
        # hook, and maybe the user tries to connect to a network service in
        # there?), don't fully swallow the exception. Also, be explicit
        # about the port number. What if they have logging turned off? Then
        # they won't see the port number in the "Greetings, program!" line.
        # They definitely won't see it if using an engine like eventlet
        # that binds to the port early.

        if website.network_port is not None:
            msg = "Is something already running on port %s? Because ..."
            if not aspen.WINDOWS:
                if website.network_port < 1024:
                    if os.geteuid() > 0:
                        msg = ("Do you have permission to bind to port %s?"
#.........这里部分代码省略.........
开发者ID:nejstastnejsistene,项目名称:aspen-python,代码行数:101,代码来源:server.py


示例9: handle

       )
    expected = "Greetings, baz!"
    actual = handle('/', '--project_root=.aspen').body
    assert actual == expected, actual


def test_double_failure_still_sets_response_dot_request():
    mk( '.aspen'
      , ('.aspen/foo.py', """
def bar(response):
    response.request
""")
      , ( '.aspen/configure-aspen.py'
        , 'import foo\nwebsite.hooks.outbound_late.register(foo.bar)'
         )
      , ('index.html', "raise heck")
       )

    # Intentionally break the website object so as to trigger a double failure.
    website = Website(['--www_root='+FSFIX, '--project_root=.aspen'])
    del website.renderer_factories

    response = website.handle(StubRequest())

    expected = 500
    actual = response.code
    assert actual == expected, actual


attach_teardown(globals())
开发者ID:jarpineh,项目名称:aspen,代码行数:30,代码来源:test_website.py


示例10: main

def main(argv=None):
    """http://aspen.io/cli/
    """
    try:

        # Do imports.
        # ===========
        # These are in here so that if you Ctrl-C during an import, the
        # KeyboardInterrupt is caught and ignored. Yes, that's how much I care.
        # No, I don't care enough to put aspen/__init__.py in here too.

        import os
        import logging
        import socket
        import sys
        import time
        import traceback
        from os.path import exists, join

        import aspen
        from aspen import restarter
        from aspen.website import Website

        
        log = logging.getLogger('aspen.cli')


        # Website
        # =======
        # User-developers get this website object inside of their simplates and
        # hooks. It provides access to configuration information in addition to
        # being a WSGI callable and holding the request/response handling
        # logic. See aspen/website.py

        if argv is None:
            argv = sys.argv[1:]
        website = Website(argv)


        # Start serving the website.
        # ==========================
        # This amounts to binding the requested socket, with logging and 
        # restarting as needed. Wrap the whole thing in a try/except to
        # do some cleanup on shutdown.

        try:
            if hasattr(socket, 'AF_UNIX'):
                if website.sockfam == socket.AF_UNIX:
                    if exists(website.address):
                        log.info("Removing stale socket.")
                        os.remove(website.address)
            if website.port is not None:
                welcome = "port %d" % website.port
            else:
                welcome = website.address
            log.info("Starting %s engine." % website.engine.name)
            website.engine.bind()
            log.warn("Greetings, program! Welcome to %s." % welcome)
            if website.changes_kill:
                log.info("Aspen will die when files change.")
                restarter.install(website)
            website.start()

        except socket.error:

            # Be friendly about port conflicts.
            # =================================
            # The traceback one gets from a port conflict is not that friendly.
            # Here's a helper to let the user know (in color?!) that a port
            # conflict is the probably the problem. But in case it isn't
            # (website.start fires the start hook, and maybe the user tries to
            # connect to a network service in there?), don't fully swallow the
            # exception. Also, be explicit about the port number. What if they
            # have logging turned off? Then they won't see the port number in
            # the "Greetings, program!" line. They definitely won't see it if
            # using an engine like eventlet that binds to the port early.

            if website.port is not None:
                msg = "Is something already running on port %s? Because ..."
                msg %= website.port
                if not aspen.WINDOWS:
                    # Assume we can use ANSI color escapes if not on Windows.
                    # XXX Maybe a bad assumption if this is going into a log 
                    # file?
                    msg = '\033[01;33m%s\033[00m' % msg
                print >> sys.stderr, msg
            raise

        except KeyboardInterrupt, SystemExit:
            pass
        except:
            traceback.print_exc()
        finally:
            if hasattr(socket, 'AF_UNIX'):
                if website.sockfam == socket.AF_UNIX:
                    if exists(website.address):
                        os.remove(website.address)
            website.stop()
开发者ID:berryp,项目名称:aspen,代码行数:98,代码来源:server.py


示例11: Website

import os
import string
import random
from os.path import basename, dirname

from aspen import Response
from aspen.website import Website

from . import gfm
from .nav import NavItem


website = Website(www_root='www', project_root='.')


# Manually register markdown renderer to work around Heroku deployment woes.
website.renderer_factories['markdown'] = gfm.Factory(website)
website.renderer_factories['jinja2'].Renderer.global_context = {
    'range': range,
    'unicode': unicode,
    'enumerate': enumerate,
    'len': len,
    'float': float,
    'type': type,
    'str': str,
}

website.renderer_default = "markdown"


def add_nav_to_website(website):
开发者ID:gratipay,项目名称:inside.gratipay.com,代码行数:31,代码来源:main.py


示例12: __init__

 def __init__(self, app):
     BaseWebsite.__init__(self)
     self.app = app
     self.version = version.get_version()
     self.configure_typecasters()
     self.configure_renderers()
开发者ID:cyberjacob,项目名称:www.gittip.com,代码行数:6,代码来源:website.py


示例13: Website

"""Configuration script for the http://aspen.io/ website.
"""
import os
import os.path
from aspen.configuration import parse
from aspen.website import Website

distribution_root = os.path.dirname(__file__)
website = Website( www_root=os.path.join(distribution_root, 'doc')
                 , project_root=os.path.join(distribution_root, 'doc', '.aspen')
                  )
opts = {}

def add_stuff_to_request_context(website, dispatch_result):

    # Define some closures for generating image markup.
    # =================================================

    def translate(src):
        if src[0] != '/':
            rel = os.path.dirname(dispatch_result.match)[len(website.www_root):]
            src = '/'.join([rel, src])
        src = opts['base'] + src
        return src

    def img(src):
        src = translate(src)
        html = '<img src="%s" />' % src
        return html

    def screenshot(short, imgtype='png', href=''):
开发者ID:jaraco,项目名称:aspen,代码行数:31,代码来源:aspen_io.py


示例14: handle

def handle(path):
    website = Website(Configuration(['fsfix']))
    return website.handle(Request.from_diesel(DieselReq(path)))
开发者ID:dowski,项目名称:aspen,代码行数:3,代码来源:__init__.py


示例15: Website

import gratipay
import gratipay.wireup
from gratipay import utils
from gratipay.cron import Cron
from gratipay.models.participant import Participant
from gratipay.security import authentication, csrf, security_headers
from gratipay.utils import erase_cookie, http_caching, i18n, set_cookie, timer
from gratipay.version import get_version
from gratipay.renderers import csv_dump, jinja2_htmlescaped, eval_, scss

import aspen
from aspen.website import Website


website = Website()


# Configure renderers
# ===================

website.renderer_default = 'unspecified'  # require explicit renderer, to avoid escaping bugs

website.renderer_factories['csv_dump'] = csv_dump.Factory(website)
website.renderer_factories['eval'] = eval_.Factory(website)
website.renderer_factories['jinja2_htmlescaped'] = jinja2_htmlescaped.Factory(website)
website.renderer_factories['scss'] = scss.Factory(website)
website.default_renderers_by_media_type['text/html'] = 'jinja2_htmlescaped'
website.default_renderers_by_media_type['text/plain'] = 'jinja2'  # unescaped is fine here
website.default_renderers_by_media_type['text/css'] = 'scss'
website.default_renderers_by_media_type['image/*'] = 'eval'
开发者ID:nishanthvijayan,项目名称:gratipay.com,代码行数:30,代码来源:main.py


示例16: test_double_failure_still_sets_response_dot_request

def test_double_failure_still_sets_response_dot_request():
    mk( '.aspen'
      , ('.aspen/foo.py', """
def bar(response):
    response.request
""")
      , ( '.aspen/configure-aspen.py'
        , 'import foo\nwebsite.hooks.outbound.append(foo.bar)'
         )
      , ('index.html', "raise heck")
       )

    # Intentionally break the website object so as to trigger a double failure.
    project_root = os.path.join(FSFIX, '.aspen')
    website = Website(['--www_root='+FSFIX, '--project_root='+project_root])
    del website.renderer_factories

    response = website.handle_safely(StubRequest())

    expected = 500
    actual = response.code
    assert actual == expected, actual


def test_website_doesnt_clobber_outbound():
    mk( ( '.aspen/configure-aspen.py'
        , 'import random\nwebsite.hooks.outbound.append(random.choice)'
         )
       )
开发者ID:gunshor,项目名称:aspen,代码行数:29,代码来源:test_website.py


示例17: Website

import base64
from urllib import quote as urlquote

from liberapay import canonize, fill_accept_header, insert_constants, utils, wireup
from liberapay.cron import Cron
from liberapay.models.community import Community
from liberapay.models.participant import Participant
from liberapay.security import authentication, csrf, x_frame_options
from liberapay.utils import erase_cookie, http_caching, i18n, set_cookie, timer
from liberapay.renderers import csv_dump, jinja2_htmlescaped, jinja2_html_jswrapped, jinja2_xml_min

import aspen
from aspen.website import Website


website = Website()


# Configure renderers
# ===================

website.renderer_default = 'unspecified'  # require explicit renderer, to avoid escaping bugs

website.renderer_factories['csv_dump'] = csv_dump.Factory(website)
website.renderer_factories['jinja2_htmlescaped'] = jinja2_htmlescaped.Factory(website)
website.renderer_factories['jinja2_html_jswrapped'] = jinja2_html_jswrapped.Factory(website)
website.renderer_factories['jinja2_xml_min'] = jinja2_xml_min.Factory(website)
website.default_renderers_by_media_type['text/html'] = 'jinja2_htmlescaped'
website.default_renderers_by_media_type['text/plain'] = 'jinja2'  # unescaped is fine here

def _assert(x):
开发者ID:kthurimella,项目名称:liberapay.com,代码行数:31,代码来源:main.py


示例18: Website

import os
from aspen.website import Website

project_root = os.path.dirname(__file__)
www_root = os.path.join(project_root, 'www')
website = Website(project_root=project_root, www_root=www_root)


# Install the eval renderer.
# ==========================

from aspen import renderers

class Renderer(renderers.Renderer):
    def render_content(self, context):
        return eval(self.compiled, globals(), context)

class Factory(renderers.Factory):
    Renderer = Renderer

website.renderer_factories['eval'] = Factory(website)
开发者ID:gratipay,项目名称:gip.rocks,代码行数:21,代码来源:gip.py


示例19: handle

def handle(path='/'):
    website = Website(['fsfix'])
    request = StubRequest(path)
    request.website = website
    response = website.handle(request)
    return response
开发者ID:falstaff84,项目名称:aspen,代码行数:6,代码来源:__init__.py


示例20: check

def check():
    website = Website(Configuration(['fsfix']))
    response = website.handle(Request.from_diesel(DieselReq()))
    return response
开发者ID:dowski,项目名称:aspen,代码行数:4,代码来源:test_website.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.Utils类代码示例发布时间:2022-05-24
下一篇:
Python utils.utcnow函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap