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


Python website.Website类代码示例

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


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


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