Pyramid - A Python web framework

Overview

Pyramid

master Travis CI Status master Documentation Status IRC Freenode

Pyramid is a small, fast, down-to-earth, open source Python web framework. It makes real-world web application development and deployment more fun, more predictable, and more productive.

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('Hello World!')

if __name__ == '__main__':
    with Configurator() as config:
        config.add_route('hello', '/')
        config.add_view(hello_world, route_name='hello')
        app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 6543, app)
    server.serve_forever()

Pyramid is a project of the Pylons Project.

Support and Documentation

See Pyramid Support and Development for documentation, reporting bugs, and getting support.

Developing and Contributing

See HACKING.txt and contributing.md for guidelines on running tests, adding features, coding style, and updating documentation when developing in or contributing to Pyramid.

License

Pyramid is offered under the BSD-derived Repoze Public License.

Authors

Pyramid is made available by Agendaless Consulting and a team of contributors.

Comments
  • Change `__str__` requirement for identity

    Change `__str__` requirement for identity

    Opening this based on @merwok's https://github.com/Pylons/pyramid/pull/3465#discussion_r330175629

    Hi! Sorry to comment after this is merged, but I was following the issue and not aware of this PR.

    I don’t understand the reason for using __str__ as the method to convert Identity to user ID.

    * `__str__` is meant to control what happens with `print`, `%s` formatting, etc.
    
    * IMO it is good practice to have `__str__` fast, without side effects, without possibility of failure (so no parsing, casting, etc)
    
    * `repr` uses `__str__` if the class doesn’t define `__repr__`
    
    * REPL, logging, others use repr or str, so seeing something that’s a user ID instead of custom str/repr output (like `<SomeIdentityClass id=blah source=value>`) in debug logs, etc. could make inspection harder
    
    * depending on the system, user ID may not be a string
    
    * calling `str(identity)` instead of `identity.some_explicit_method()` seems a bit obscure (not discoverable)
    

    If people agree with the disadvantages here, could this API decision be reconsidered?

    Some previous discussions:

    https://github.com/Pylons/pyramid/issues/3422#issuecomment-443840114 https://github.com/Pylons/pyramid/pull/3465#issuecomment-511140572

    opened by luhn 84
  • alchemy scaffold updates

    alchemy scaffold updates

    This is a WIP to bring the alchemy scaffold in line with best practices.

    • [x] Remove scoped sessions.
    • [x] Connect session to request method.
    • [x] Switch to jinja2 templates.
    • [x] Add a meta module or package to avoid any circular references when importing.
    • [x] Switch models into a package instead of a module.
    • [x] Scan docs and tutorials for updates related to the changes. Here is the list of files. See comment below.
      • [x] whatsnew-1.6.rst (Scaffolding Enhancements and Documentation Enhancements sections)
      • [x] Quick Tour sqla_demo generated from scaffold and its associated files in quick_tour/sqla_demo/. Note that there are some comments inserted in these files for Sphinx rendering. See quick_tour.rst, Databases section.
      • [x] quick_tour.rst, Databases section
      • [x] tutorials/wiki2/src/*/tutorial/[~~authorization~~|~~basiclayout~~|~~models~~|~~tests~~|~~views~~]/ (5 directories)
      • [x] tutorials/wiki2/authorization.rst (13 occurrences)
      • [x] tutorials/wiki2/basiclayout.rst (2 occurrences)
      • [x] tutorials/wiki2/definingmodels.rst (9 occurrences)
      • [x] tutorials/wiki2/definingviews.rst (9 occurrences)
      • [x] tutorials/wiki2/design.rst (4 occurrences)
      • [x] tutorials/wiki2/tests.rst
    • Pyramid Cookbook recipes
      • [x] http://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/auth/wiki2_auth.html (Add a note that this recipe will no longer apply when Pyramid 1.7 is released, and is most likely out of date since Pyramid 1.3. Or maybe just delete it?)
    • [x] Add configure_mappers when initializing the session.
    opened by mmerickel 71
  • Auth post-mortem (Pyramid 2.0)

    Auth post-mortem (Pyramid 2.0)

    Hi guys! I'm interested in taking a crack at reworking the auth system for Pyramid 2.0, based on the Auth API Post-Mortem. Would you be open to starting a discussion?

    I like Pyramid a lot and would love to see a new auth API in 2.0, as mentioned in #2362. Hopefully I'm not being too brash, barging through the front door as a first-time contributor and asking to remodel kitchen. I want to be respectful of your time; once we hash out the details I'm confident I can make it happen independently with minimal time investment from you.

    opened by luhn 53
  • Protect against Session Fixation and session data leakage when crossing privilege boundaries

    Protect against Session Fixation and session data leakage when crossing privilege boundaries

    This will invalidate the session in the SessionAuthenticationPolicy().remember(), ensuring that all the data is copied over to the new session. This will ensure that for server side sessions which have a session ID, a new session ID is granted when going from an unauthenticated user to an authenticated user. For client side sessions this will simply do a little extra work but ultimately be a no-op.

    Fixes #1569

    security 
    opened by dstufft 46
  • Security policy implementation

    Security policy implementation

    • [x] ISecurityPolicy
    • [x] Configurator.set_security_policy
    • [x] bwcompat security policy
    • [x] Request properties
    • [x] Security view deriver
    • [x] Built-in policies and helpers
    • [x] Narrative docs
    • [x] DeprecationWarning / zope.deprecation

    Closes #3422

    opened by luhn 44
  • Documentation change: easy_install to pip

    Documentation change: easy_install to pip

    Update the documentation to use pip instead of easy_install.

    Work should be pushed to the branch docs/easy-install-to-pip.2104.

    Branch docs/easy-install-to-pip.2104 will eventually be merged to master upon completion of the items listed below.

    Add omitted items to the lists.

    List of related issues and PRs.

    • https://github.com/Pylons/pyramid/issues/575
    • https://github.com/Pylons/pyramid/issues/1454
    • https://github.com/Pylons/pyramid/issues/121
    • https://github.com/Pylons/pyramid/pull/2024

    List of documentation and official tutorials

    (Pretty much every step for tutorials needs updating, so only the indices are shown for brevity.)

    opened by stevepiercy 37
  • accept handling during view lookup is unpredictable

    accept handling during view lookup is unpredictable

    As per the examples in #1259, it should be clear that the accept handling in Pyramid is somewhat unpredictable. It is a smell that the view invoked is somewhat dependent on the ordering of a set. When defining some views with accept predicates, a user should be able to have a solid understanding of when each view will be invoked, and possibly be able to influence what happens what a client simply asks for */* or does not include an Accept header.

    opened by mmerickel 37
  • route_prefix doesn't allow the prefix pattern to match without a trailing slash

    route_prefix doesn't allow the prefix pattern to match without a trailing slash

    The issue here is an ambiguity in handling route_prefix. In general, things work correctly:

    def routes(config):
        config.add_route('add_user', '/add')
    
    config.include(routes, route_prefix='/users')
    
    # resulting pattern: '/users/add'
    

    The ambiguity arises when the included function attempts to add a route using the pattern '/' or '' (an empty string). Pyramid elects to treat the prefix as a container.

    def routes(config):
        config.add_route('users', '/')
    
    config.include(routes, route_prefix='/users')
    
    # resulting pattern: '/users/'
    

    Remember that in Pyramid's config.add_route there is no difference between prepending a '/' or leaving no prefix. Thus, the two route definitions below result in the same url being matched and generated.

    config.add_route('r1', '/route')
    config.add_route('r2', 'route')
    

    There are 4 possible use cases to account for when looking at the issue.

    Case 1

    def routes(config):
        config.add_route('route', '')
    
    config.include(routes, route_prefix='/prefix')
    

    Case 2

    def routes(config):
        config.add_route('route', '/')
    
    config.include(routes, route_prefix='/prefix')
    

    Case 3

    def routes(config):
        config.add_route('route', '')
    
    config.include(routes, route_prefix='/prefix/')
    

    Case 4

    def routes(config):
        config.add_route('route', '/')
    
    config.include(routes, route_prefix='/prefix/')
    

    Workaround

    Pyramid currently treats the route prefix as a container, thus the resulting route will always be appended with a '/'. This may not be ideal, but it at least allows for a workaround where the user can add their own route (at the level of the include):

    def routes(config):
        config.add_route('add', '/add')
    
    config.include(routes, route_prefix='/users')
    config.add_route('users', '/users')
    

    If there is a clear way to handle each use-case, and document it as such, then it may be possible to change this behavior but to me it's hard to expect a user to "do the right thing" with case 2 due to the way pyramid currently handles add_route patterns with and without a prefixed slash.

    feature-request 
    opened by mmerickel 36
  • wiki2 tutorial - Failed building wheel for bcrypt

    wiki2 tutorial - Failed building wheel for bcrypt

    Unable to install bcrypt in Ubuntu 12.04 with Python 3.5.1.

    Maybe it would be useful to write some note about this possible issue in Ubuntu 12.04.

    Steps to reproduce the problem

    • Follow wiki2's steps until installing bcrypt.
    • pip will show long error message.

    Solution

    Set dependency to py_bcrypt instead of bcrypt in setup.py.

    opened by viniciusban 33
  • update docs to use security policy

    update docs to use security policy

    • [X] rename identify to authenticated_identity on ISecurityPolicy
    • [X] quick_tutorial
    • [x] sync cookiecutter to wiki tutorial
    • [x] use security policy in wiki tutorial
    • [X] sync cookiecutter to wiki2
    • [X] use security policy in wiki2 tutorial
    • [x] revise security chapter - this is at least partially complete
    • [x] sync cookiecutter to starter project

    rendered: https://mmerickel-pyramid-fork.readthedocs.io/en/security-docs/

    fixes #3548

    opened by mmerickel 31
  • Pass vars to logging.config.fileConfig

    Pass vars to logging.config.fileConfig

    This allows one to set up a logging configuration that is parameterized based on variables specified on the command-line.

    e.g.: the application .ini file could have:

    [logger_root]
    level = %(LOGGING_LOGGER_ROOT_LEVEL)s
    handlers = console
    
    [handler_console]
    class = StreamHandler
    args = (sys.stderr,)
    level = %(LOGGING_HANDLER_CONSOLE_LEVEL)s
    formatter = generic
    

    This app could be launched with:

    pserve development.ini LOGGING_LOGGER_ROOT_LEVEL=DEBUG LOGGING_HANDLER_CONSOLE_LEVEL=DEBUG
    

    Cc: @mmerickel, @sontek, @sudarkoff, @sseg, @aconrad

    opened by msabramo 31
  • context matching in views and inheritance (traversal)

    context matching in views and inheritance (traversal)

    Hello,

    given 2 ressources and a @view_config:

    class A:
        ...
    
    class B(A):
        ...
    
    @view_config(context=A, name='foo')
    def foo():
        ...
    

    is there a way to match /someB/foo to A foo() if /someB/foo resolves to context B, but no @view_config(context=B, name='foo') has been defined (but as B is a child of A it could matches foo() registered on A) ?

    Thanks

    opened by silenius 1
  • pserve out function always prints to stderr

    pserve out function always prints to stderr

    In https://github.com/Pylons/pyramid/blob/master/src/pyramid/scripts/pserve.py#L146

    The script outputs everything to the stderr file descriptor. If you redirect the stdout and stderr stream to your logger, then for example the 'Starting server' message gets logged as an error.

    I would propose to split the out function into two in PServeCommand:

        def out(self, msg):  # pragma: no cover
            if self.args.verbose > 0:
                print(msg)
    
        def out_err(self, msg):  # pragma: no cover
            if self.args.verbose > 0:
                print(msg, file=sys.stderr)
    

    And call the out_err function to print 'You must give a config file'.

    In the rest of the file all of the other prints could also be changed to stdout, so that hey would no longer output starting/serving messages to stderr.

    In other scripts even errors get printed to stdout, so this could also be applied in other scripts where applicable: https://github.com/Pylons/pyramid/blob/master/src/pyramid/scripts/prequest.py#L135

    I can create a PR if such a changes would be permitted.

    opened by markonose 3
  • tutorial/forms got ERROR:waitress:Exception while serving /favicon.ico

    tutorial/forms got ERROR:waitress:Exception while serving /favicon.ico

    Get Support

    To get help or technical support, see Get Support.

    Bug Report

    Please search the issue tracker for similar issues before submitting a new issue.

    Describe the bug Try to run tutorial/forms, got this exception.

    To Reproduce C:\projects\quick_tutorial\forms>%VENV%\scripts\pserve development.ini --reload Starting monitor for PID 9444. Starting server in PID 14480. ERROR:waitress:Exception while serving /favicon.ico Traceback (most recent call last): File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\tweens.py", line 13, in _error_handler response = request.invoke_exception_view(exc_info) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\view.py", line 786, in invoke_exception_view raise HTTPNotFound pyramid.httpexceptions.HTTPNotFound: The resource could not be found.

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "c:\projects\quick_tutorial\env\lib\site-packages\waitress\channel.py", line 426, in service task.service() File "c:\projects\quick_tutorial\env\lib\site-packages\waitress\task.py", line 168, in service self.execute() File "c:\projects\quick_tutorial\env\lib\site-packages\waitress\task.py", line 434, in execute app_iter = self.channel.server.application(environ, start_response) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\router.py", line 270, in call response = self.execution_policy(environ, self) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\router.py", line 276, in default_execution_policy return router.invoke_request(request) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\router.py", line 245, in invoke_request response = handle_request(request) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid_debugtoolbar\toolbar.py", line 238, in toolbar_tween return handler(request) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\tweens.py", line 43, in excview_tween response = _error_handler(request, exc) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\tweens.py", line 17, in _error_handler reraise(*exc_info) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\util.py", line 733, in reraise raise value File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\tweens.py", line 41, in excview_tween response = handler(request) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\router.py", line 143, in handle_request response = _call_view( File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\view.py", line 674, in _call_view response = view_callable(context, request) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\viewderivers.py", line 427, in rendered_view result = view(context, request) File "c:\projects\quick_tutorial\env\lib\site-packages\pyramid\viewderivers.py", line 113, in _class_requestonly_view response = getattr(inst, attr)() File "c:\projects\quick_tutorial\forms\tutorial\views.py", line 64, in wikipage_view page = pages[uid] KeyError: 'favicon.ico'

    opened by LogiFarmer 3
  • Detect routes that collide during registration

    Detect routes that collide during registration

    I've recently been hit by this problem, after changing the ordering in which controllers were registered, some routes weren't called.

    This is because some routes using pattern matching were registered before other routes. For instance route /users/{user_id} registered before /users/export

    Of course this can be fixed by changing the ordering in which routes get registered but it is something that is probably bugging other users and that can be detected.

    I was able to have a unit test that would detect this in our project (by parsing proutes output) but I was wondering if that is a feature that could be of interest to be baked in pyramid itself? I'd be happy to hack on this, please just point me to a starting point in the codebase

    opened by bagerard 5
  • AuthTktCookieHelper debug

    AuthTktCookieHelper debug

    While migrating to the new security policy, I noticed https://github.com/Pylons/pyramid/blob/master/src/pyramid/authentication.py#L950-L955 but it is not used in the constructor, leading to:

    TypeError: __init__() got an unexpected keyword argument 'debug'

    Is it a bug in the documentation (debug isn't supported anymore?) or a forget while migration to the new authorization/authentication stuff?

    opened by silenius 1
Owner
Pylons Project
The Pylons Project is composed of a disparate group of project leaders with experience going back to the very start of Python web frameworks.
Pylons Project
Asita is a web application framework for python based on express-js framework.

Asita is a web application framework for python. It is designed to be easy to use and be more easy for javascript users to use python frameworks because it is based on express-js framework.

Mattéo 4 Nov 16, 2021
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Jan 8, 2023
Fast, asynchronous and elegant Python web framework.

Warning: This project is being completely re-written. If you're curious about the progress, reach me on Slack. Vibora is a fast, asynchronous and eleg

vibora.io 5.7k Jan 8, 2023
The Python micro framework for building web applications.

Flask Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to co

The Pallets Projects 61.5k Jan 6, 2023
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Tornado Web Server Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. By using non-blocking ne

null 20.9k Jan 1, 2023
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Dec 28, 2022
bottle.py is a fast and simple micro-framework for python web-applications.

Bottle: Python Web Framework Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module a

Bottle Micro Web Framework 7.8k Dec 31, 2022
The Modern And Developer Centric Python Web Framework. Be sure to read the documentation and join the Slack channel questions: http://slack.masoniteproject.com

NOTE: Masonite 2.3 is no longer compatible with the masonite-cli tool. Please uninstall that by running pip uninstall masonite-cli. If you do not unin

Masonite 1.9k Jan 4, 2023
Free and open source full-stack enterprise framework for agile development of secure database-driven web-based applications, written and programmable in Python.

Readme web2py is a free open source full-stack framework for rapid development of fast, scalable, secure and portable database-driven web-based applic

null 2k Dec 31, 2022
Sierra is a lightweight Python framework for building and integrating web applications

A lightweight Python framework for building and Integrating Web Applications. Sierra is a Python3 library for building and integrating web applications with HTML and CSS using simple enough syntax. You can develop your web applications with Python, taking advantage of its functionalities and integrating them to the fullest.

null 83 Sep 23, 2022
Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints.

Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints. check parameters and generate API documents automatically. Flask Sugar是一个基于flask,pyddantic,类型注解的API框架, 可以检查参数并自动生成API文档

null 162 Dec 26, 2022
Fast⚡, simple and light💡weight ASGI micro🔬 web🌏-framework for Python🐍.

NanoASGI Asynchronous Python Web Framework NanoASGI is a fast ⚡ , simple and light ?? weight ASGI micro ?? web ?? -framework for Python ?? . It is dis

Kavindu Santhusa 8 Jun 16, 2022
Dazzler is a Python async UI/Web framework built with aiohttp and react.

Dazzler is a Python async UI/Web framework built with aiohttp and react. Create dazzling fast pages with a layout of Python components and bindings to update from the backend.

Philippe Duval 17 Oct 18, 2022
Appier is an object-oriented Python web framework built for super fast app development.

Joyful Python Web App development Appier is an object-oriented Python web framework built for super fast app development. It's as lightweight as possi

Hive Solutions 122 Dec 22, 2022
Chisel is a light-weight Python WSGI application framework built for creating well-documented, schema-validated JSON web APIs

chisel Chisel is a light-weight Python WSGI application framework built for creating well-documented, schema-validated JSON web APIs. Here are its fea

Craig Hobbs 2 Dec 2, 2021
APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects

APIFlask APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects. It's easy to use, highly customizable, ORM/O

Grey Li 705 Jan 4, 2023
A public API written in Python using the Flask web framework to determine the direction of a road sign using AI

python-public-API This repository is a public API for solving the problem of the final of the AIIJC competition. The task is to create an AI for the c

Lev 1 Nov 8, 2021
Bionic is Python Framework for crafting beautiful, fast user experiences for web and is free and open source

Bionic is fast. It's powered core python without any extra dependencies. Bionic offers stateful hot reload, allowing you to make changes to your code and see the results instantly without restarting your app or losing its state.

 ⚓ 0 Mar 5, 2022
Asita is a web application framework for python.

What is Asita ? Asita is a web application framework for python. It is designed to be easy to use and be more easy for javascript users to use python

Mattéo 4 Nov 16, 2021