
6482 changed files with 720174 additions and 0 deletions
File diff suppressed because it is too large
@ -0,0 +1 @@ |
|||||
|
pip |
@ -0,0 +1,27 @@ |
|||||
|
Copyright (c) Django Software Foundation and individual contributors. |
||||
|
All rights reserved. |
||||
|
|
||||
|
Redistribution and use in source and binary forms, with or without modification, |
||||
|
are permitted provided that the following conditions are met: |
||||
|
|
||||
|
1. Redistributions of source code must retain the above copyright notice, |
||||
|
this list of conditions and the following disclaimer. |
||||
|
|
||||
|
2. Redistributions in binary form must reproduce the above copyright |
||||
|
notice, this list of conditions and the following disclaimer in the |
||||
|
documentation and/or other materials provided with the distribution. |
||||
|
|
||||
|
3. Neither the name of Django nor the names of its contributors may be used |
||||
|
to endorse or promote products derived from this software without |
||||
|
specific prior written permission. |
||||
|
|
||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
||||
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
||||
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR |
||||
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
||||
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
||||
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON |
||||
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
||||
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
||||
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
@ -0,0 +1,290 @@ |
|||||
|
Django is licensed under the three-clause BSD license; see the file |
||||
|
LICENSE for details. |
||||
|
|
||||
|
Django includes code from the Python standard library, which is licensed under |
||||
|
the Python license, a permissive open source license. The copyright and license |
||||
|
is included below for compliance with Python's terms. |
||||
|
|
||||
|
---------------------------------------------------------------------- |
||||
|
|
||||
|
Copyright (c) 2001-present Python Software Foundation; All Rights Reserved |
||||
|
|
||||
|
A. HISTORY OF THE SOFTWARE |
||||
|
========================== |
||||
|
|
||||
|
Python was created in the early 1990s by Guido van Rossum at Stichting |
||||
|
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands |
||||
|
as a successor of a language called ABC. Guido remains Python's |
||||
|
principal author, although it includes many contributions from others. |
||||
|
|
||||
|
In 1995, Guido continued his work on Python at the Corporation for |
||||
|
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) |
||||
|
in Reston, Virginia where he released several versions of the |
||||
|
software. |
||||
|
|
||||
|
In May 2000, Guido and the Python core development team moved to |
||||
|
BeOpen.com to form the BeOpen PythonLabs team. In October of the same |
||||
|
year, the PythonLabs team moved to Digital Creations, which became |
||||
|
Zope Corporation. In 2001, the Python Software Foundation (PSF, see |
||||
|
https://www.python.org/psf/) was formed, a non-profit organization |
||||
|
created specifically to own Python-related Intellectual Property. |
||||
|
Zope Corporation was a sponsoring member of the PSF. |
||||
|
|
||||
|
All Python releases are Open Source (see http://www.opensource.org for |
||||
|
the Open Source Definition). Historically, most, but not all, Python |
||||
|
releases have also been GPL-compatible; the table below summarizes |
||||
|
the various releases. |
||||
|
|
||||
|
Release Derived Year Owner GPL- |
||||
|
from compatible? (1) |
||||
|
|
||||
|
0.9.0 thru 1.2 1991-1995 CWI yes |
||||
|
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes |
||||
|
1.6 1.5.2 2000 CNRI no |
||||
|
2.0 1.6 2000 BeOpen.com no |
||||
|
1.6.1 1.6 2001 CNRI yes (2) |
||||
|
2.1 2.0+1.6.1 2001 PSF no |
||||
|
2.0.1 2.0+1.6.1 2001 PSF yes |
||||
|
2.1.1 2.1+2.0.1 2001 PSF yes |
||||
|
2.1.2 2.1.1 2002 PSF yes |
||||
|
2.1.3 2.1.2 2002 PSF yes |
||||
|
2.2 and above 2.1.1 2001-now PSF yes |
||||
|
|
||||
|
Footnotes: |
||||
|
|
||||
|
(1) GPL-compatible doesn't mean that we're distributing Python under |
||||
|
the GPL. All Python licenses, unlike the GPL, let you distribute |
||||
|
a modified version without making your changes open source. The |
||||
|
GPL-compatible licenses make it possible to combine Python with |
||||
|
other software that is released under the GPL; the others don't. |
||||
|
|
||||
|
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, |
||||
|
because its license has a choice of law clause. According to |
||||
|
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 |
||||
|
is "not incompatible" with the GPL. |
||||
|
|
||||
|
Thanks to the many outside volunteers who have worked under Guido's |
||||
|
direction to make these releases possible. |
||||
|
|
||||
|
|
||||
|
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON |
||||
|
=============================================================== |
||||
|
|
||||
|
Python software and documentation are licensed under the |
||||
|
Python Software Foundation License Version 2. |
||||
|
|
||||
|
Starting with Python 3.8.6, examples, recipes, and other code in |
||||
|
the documentation are dual licensed under the PSF License Version 2 |
||||
|
and the Zero-Clause BSD license. |
||||
|
|
||||
|
Some software incorporated into Python is under different licenses. |
||||
|
The licenses are listed with code falling under that license. |
||||
|
|
||||
|
|
||||
|
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 |
||||
|
-------------------------------------------- |
||||
|
|
||||
|
1. This LICENSE AGREEMENT is between the Python Software Foundation |
||||
|
("PSF"), and the Individual or Organization ("Licensee") accessing and |
||||
|
otherwise using this software ("Python") in source or binary form and |
||||
|
its associated documentation. |
||||
|
|
||||
|
2. Subject to the terms and conditions of this License Agreement, PSF hereby |
||||
|
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, |
||||
|
analyze, test, perform and/or display publicly, prepare derivative works, |
||||
|
distribute, and otherwise use Python alone or in any derivative version, |
||||
|
provided, however, that PSF's License Agreement and PSF's notice of copyright, |
||||
|
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, |
||||
|
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Python Software Foundation; |
||||
|
All Rights Reserved" are retained in Python alone or in any derivative version |
||||
|
prepared by Licensee. |
||||
|
|
||||
|
3. In the event Licensee prepares a derivative work that is based on |
||||
|
or incorporates Python or any part thereof, and wants to make |
||||
|
the derivative work available to others as provided herein, then |
||||
|
Licensee hereby agrees to include in any such work a brief summary of |
||||
|
the changes made to Python. |
||||
|
|
||||
|
4. PSF is making Python available to Licensee on an "AS IS" |
||||
|
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR |
||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND |
||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS |
||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT |
||||
|
INFRINGE ANY THIRD PARTY RIGHTS. |
||||
|
|
||||
|
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |
||||
|
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS |
||||
|
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, |
||||
|
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. |
||||
|
|
||||
|
6. This License Agreement will automatically terminate upon a material |
||||
|
breach of its terms and conditions. |
||||
|
|
||||
|
7. Nothing in this License Agreement shall be deemed to create any |
||||
|
relationship of agency, partnership, or joint venture between PSF and |
||||
|
Licensee. This License Agreement does not grant permission to use PSF |
||||
|
trademarks or trade name in a trademark sense to endorse or promote |
||||
|
products or services of Licensee, or any third party. |
||||
|
|
||||
|
8. By copying, installing or otherwise using Python, Licensee |
||||
|
agrees to be bound by the terms and conditions of this License |
||||
|
Agreement. |
||||
|
|
||||
|
|
||||
|
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 |
||||
|
------------------------------------------- |
||||
|
|
||||
|
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 |
||||
|
|
||||
|
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an |
||||
|
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the |
||||
|
Individual or Organization ("Licensee") accessing and otherwise using |
||||
|
this software in source or binary form and its associated |
||||
|
documentation ("the Software"). |
||||
|
|
||||
|
2. Subject to the terms and conditions of this BeOpen Python License |
||||
|
Agreement, BeOpen hereby grants Licensee a non-exclusive, |
||||
|
royalty-free, world-wide license to reproduce, analyze, test, perform |
||||
|
and/or display publicly, prepare derivative works, distribute, and |
||||
|
otherwise use the Software alone or in any derivative version, |
||||
|
provided, however, that the BeOpen Python License is retained in the |
||||
|
Software, alone or in any derivative version prepared by Licensee. |
||||
|
|
||||
|
3. BeOpen is making the Software available to Licensee on an "AS IS" |
||||
|
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR |
||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND |
||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS |
||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT |
||||
|
INFRINGE ANY THIRD PARTY RIGHTS. |
||||
|
|
||||
|
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE |
||||
|
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS |
||||
|
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY |
||||
|
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. |
||||
|
|
||||
|
5. This License Agreement will automatically terminate upon a material |
||||
|
breach of its terms and conditions. |
||||
|
|
||||
|
6. This License Agreement shall be governed by and interpreted in all |
||||
|
respects by the law of the State of California, excluding conflict of |
||||
|
law provisions. Nothing in this License Agreement shall be deemed to |
||||
|
create any relationship of agency, partnership, or joint venture |
||||
|
between BeOpen and Licensee. This License Agreement does not grant |
||||
|
permission to use BeOpen trademarks or trade names in a trademark |
||||
|
sense to endorse or promote products or services of Licensee, or any |
||||
|
third party. As an exception, the "BeOpen Python" logos available at |
||||
|
http://www.pythonlabs.com/logos.html may be used according to the |
||||
|
permissions granted on that web page. |
||||
|
|
||||
|
7. By copying, installing or otherwise using the software, Licensee |
||||
|
agrees to be bound by the terms and conditions of this License |
||||
|
Agreement. |
||||
|
|
||||
|
|
||||
|
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 |
||||
|
--------------------------------------- |
||||
|
|
||||
|
1. This LICENSE AGREEMENT is between the Corporation for National |
||||
|
Research Initiatives, having an office at 1895 Preston White Drive, |
||||
|
Reston, VA 20191 ("CNRI"), and the Individual or Organization |
||||
|
("Licensee") accessing and otherwise using Python 1.6.1 software in |
||||
|
source or binary form and its associated documentation. |
||||
|
|
||||
|
2. Subject to the terms and conditions of this License Agreement, CNRI |
||||
|
hereby grants Licensee a nonexclusive, royalty-free, world-wide |
||||
|
license to reproduce, analyze, test, perform and/or display publicly, |
||||
|
prepare derivative works, distribute, and otherwise use Python 1.6.1 |
||||
|
alone or in any derivative version, provided, however, that CNRI's |
||||
|
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) |
||||
|
1995-2001 Corporation for National Research Initiatives; All Rights |
||||
|
Reserved" are retained in Python 1.6.1 alone or in any derivative |
||||
|
version prepared by Licensee. Alternately, in lieu of CNRI's License |
||||
|
Agreement, Licensee may substitute the following text (omitting the |
||||
|
quotes): "Python 1.6.1 is made available subject to the terms and |
||||
|
conditions in CNRI's License Agreement. This Agreement together with |
||||
|
Python 1.6.1 may be located on the internet using the following |
||||
|
unique, persistent identifier (known as a handle): 1895.22/1013. This |
||||
|
Agreement may also be obtained from a proxy server on the internet |
||||
|
using the following URL: http://hdl.handle.net/1895.22/1013". |
||||
|
|
||||
|
3. In the event Licensee prepares a derivative work that is based on |
||||
|
or incorporates Python 1.6.1 or any part thereof, and wants to make |
||||
|
the derivative work available to others as provided herein, then |
||||
|
Licensee hereby agrees to include in any such work a brief summary of |
||||
|
the changes made to Python 1.6.1. |
||||
|
|
||||
|
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" |
||||
|
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR |
||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND |
||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS |
||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT |
||||
|
INFRINGE ANY THIRD PARTY RIGHTS. |
||||
|
|
||||
|
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |
||||
|
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS |
||||
|
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, |
||||
|
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. |
||||
|
|
||||
|
6. This License Agreement will automatically terminate upon a material |
||||
|
breach of its terms and conditions. |
||||
|
|
||||
|
7. This License Agreement shall be governed by the federal |
||||
|
intellectual property law of the United States, including without |
||||
|
limitation the federal copyright law, and, to the extent such |
||||
|
U.S. federal law does not apply, by the law of the Commonwealth of |
||||
|
Virginia, excluding Virginia's conflict of law provisions. |
||||
|
Notwithstanding the foregoing, with regard to derivative works based |
||||
|
on Python 1.6.1 that incorporate non-separable material that was |
||||
|
previously distributed under the GNU General Public License (GPL), the |
||||
|
law of the Commonwealth of Virginia shall govern this License |
||||
|
Agreement only as to issues arising under or with respect to |
||||
|
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this |
||||
|
License Agreement shall be deemed to create any relationship of |
||||
|
agency, partnership, or joint venture between CNRI and Licensee. This |
||||
|
License Agreement does not grant permission to use CNRI trademarks or |
||||
|
trade name in a trademark sense to endorse or promote products or |
||||
|
services of Licensee, or any third party. |
||||
|
|
||||
|
8. By clicking on the "ACCEPT" button where indicated, or by copying, |
||||
|
installing or otherwise using Python 1.6.1, Licensee agrees to be |
||||
|
bound by the terms and conditions of this License Agreement. |
||||
|
|
||||
|
ACCEPT |
||||
|
|
||||
|
|
||||
|
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 |
||||
|
-------------------------------------------------- |
||||
|
|
||||
|
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, |
||||
|
The Netherlands. All rights reserved. |
||||
|
|
||||
|
Permission to use, copy, modify, and distribute this software and its |
||||
|
documentation for any purpose and without fee is hereby granted, |
||||
|
provided that the above copyright notice appear in all copies and that |
||||
|
both that copyright notice and this permission notice appear in |
||||
|
supporting documentation, and that the name of Stichting Mathematisch |
||||
|
Centrum or CWI not be used in advertising or publicity pertaining to |
||||
|
distribution of the software without specific, written prior |
||||
|
permission. |
||||
|
|
||||
|
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO |
||||
|
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND |
||||
|
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE |
||||
|
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
||||
|
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
||||
|
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
||||
|
|
||||
|
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION |
||||
|
---------------------------------------------------------------------- |
||||
|
|
||||
|
Permission to use, copy, modify, and/or distribute this software for any |
||||
|
purpose with or without fee is hereby granted. |
||||
|
|
||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH |
||||
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY |
||||
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, |
||||
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM |
||||
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR |
||||
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR |
||||
|
PERFORMANCE OF THIS SOFTWARE. |
@ -0,0 +1,100 @@ |
|||||
|
Metadata-Version: 2.1 |
||||
|
Name: Django |
||||
|
Version: 4.0.3 |
||||
|
Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. |
||||
|
Home-page: https://www.djangoproject.com/ |
||||
|
Author: Django Software Foundation |
||||
|
Author-email: foundation@djangoproject.com |
||||
|
License: BSD-3-Clause |
||||
|
Project-URL: Documentation, https://docs.djangoproject.com/ |
||||
|
Project-URL: Release notes, https://docs.djangoproject.com/en/stable/releases/ |
||||
|
Project-URL: Funding, https://www.djangoproject.com/fundraising/ |
||||
|
Project-URL: Source, https://github.com/django/django |
||||
|
Project-URL: Tracker, https://code.djangoproject.com/ |
||||
|
Platform: UNKNOWN |
||||
|
Classifier: Development Status :: 5 - Production/Stable |
||||
|
Classifier: Environment :: Web Environment |
||||
|
Classifier: Framework :: Django |
||||
|
Classifier: Intended Audience :: Developers |
||||
|
Classifier: License :: OSI Approved :: BSD License |
||||
|
Classifier: Operating System :: OS Independent |
||||
|
Classifier: Programming Language :: Python |
||||
|
Classifier: Programming Language :: Python :: 3 |
||||
|
Classifier: Programming Language :: Python :: 3 :: Only |
||||
|
Classifier: Programming Language :: Python :: 3.8 |
||||
|
Classifier: Programming Language :: Python :: 3.9 |
||||
|
Classifier: Programming Language :: Python :: 3.10 |
||||
|
Classifier: Topic :: Internet :: WWW/HTTP |
||||
|
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content |
||||
|
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI |
||||
|
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks |
||||
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules |
||||
|
Requires-Python: >=3.8 |
||||
|
License-File: LICENSE |
||||
|
License-File: LICENSE.python |
||||
|
License-File: AUTHORS |
||||
|
Requires-Dist: asgiref (<4,>=3.4.1) |
||||
|
Requires-Dist: sqlparse (>=0.2.2) |
||||
|
Requires-Dist: backports.zoneinfo ; python_version < "3.9" |
||||
|
Requires-Dist: tzdata ; sys_platform == "win32" |
||||
|
Provides-Extra: argon2 |
||||
|
Requires-Dist: argon2-cffi (>=19.1.0) ; extra == 'argon2' |
||||
|
Provides-Extra: bcrypt |
||||
|
Requires-Dist: bcrypt ; extra == 'bcrypt' |
||||
|
|
||||
|
====== |
||||
|
Django |
||||
|
====== |
||||
|
|
||||
|
Django is a high-level Python web framework that encourages rapid development |
||||
|
and clean, pragmatic design. Thanks for checking it out. |
||||
|
|
||||
|
All documentation is in the "``docs``" directory and online at |
||||
|
https://docs.djangoproject.com/en/stable/. If you're just getting started, |
||||
|
here's how we recommend you read the docs: |
||||
|
|
||||
|
* First, read ``docs/intro/install.txt`` for instructions on installing Django. |
||||
|
|
||||
|
* Next, work through the tutorials in order (``docs/intro/tutorial01.txt``, |
||||
|
``docs/intro/tutorial02.txt``, etc.). |
||||
|
|
||||
|
* If you want to set up an actual deployment server, read |
||||
|
``docs/howto/deployment/index.txt`` for instructions. |
||||
|
|
||||
|
* You'll probably want to read through the topical guides (in ``docs/topics``) |
||||
|
next; from there you can jump to the HOWTOs (in ``docs/howto``) for specific |
||||
|
problems, and check out the reference (``docs/ref``) for gory details. |
||||
|
|
||||
|
* See ``docs/README`` for instructions on building an HTML version of the docs. |
||||
|
|
||||
|
Docs are updated rigorously. If you find any problems in the docs, or think |
||||
|
they should be clarified in any way, please take 30 seconds to fill out a |
||||
|
ticket here: https://code.djangoproject.com/newticket |
||||
|
|
||||
|
To get more help: |
||||
|
|
||||
|
* Join the ``#django`` channel on ``irc.libera.chat``. Lots of helpful people |
||||
|
hang out there. See https://web.libera.chat if you're new to IRC. |
||||
|
|
||||
|
* Join the django-users mailing list, or read the archives, at |
||||
|
https://groups.google.com/group/django-users. |
||||
|
|
||||
|
To contribute to Django: |
||||
|
|
||||
|
* Check out https://docs.djangoproject.com/en/dev/internals/contributing/ for |
||||
|
information about getting involved. |
||||
|
|
||||
|
To run Django's test suite: |
||||
|
|
||||
|
* Follow the instructions in the "Unit tests" section of |
||||
|
``docs/internals/contributing/writing-code/unit-tests.txt``, published online at |
||||
|
https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/#running-the-unit-tests |
||||
|
|
||||
|
Supporting the Development of Django |
||||
|
==================================== |
||||
|
|
||||
|
Django's development depends on your contributions. |
||||
|
|
||||
|
If you depend on Django, remember to support the Django Software Foundation: https://www.djangoproject.com/fundraising/ |
||||
|
|
||||
|
|
File diff suppressed because it is too large
@ -0,0 +1,5 @@ |
|||||
|
Wheel-Version: 1.0 |
||||
|
Generator: bdist_wheel (0.37.0) |
||||
|
Root-Is-Purelib: true |
||||
|
Tag: py3-none-any |
||||
|
|
@ -0,0 +1,3 @@ |
|||||
|
[console_scripts] |
||||
|
django-admin = django.core.management:execute_from_command_line |
||||
|
|
@ -0,0 +1 @@ |
|||||
|
django |
Binary file not shown.
@ -0,0 +1 @@ |
|||||
|
pip |
@ -0,0 +1,27 @@ |
|||||
|
Copyright (c) Django Software Foundation and individual contributors. |
||||
|
All rights reserved. |
||||
|
|
||||
|
Redistribution and use in source and binary forms, with or without modification, |
||||
|
are permitted provided that the following conditions are met: |
||||
|
|
||||
|
1. Redistributions of source code must retain the above copyright notice, |
||||
|
this list of conditions and the following disclaimer. |
||||
|
|
||||
|
2. Redistributions in binary form must reproduce the above copyright |
||||
|
notice, this list of conditions and the following disclaimer in the |
||||
|
documentation and/or other materials provided with the distribution. |
||||
|
|
||||
|
3. Neither the name of Django nor the names of its contributors may be used |
||||
|
to endorse or promote products derived from this software without |
||||
|
specific prior written permission. |
||||
|
|
||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
||||
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
||||
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR |
||||
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
||||
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
||||
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON |
||||
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
||||
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
||||
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
@ -0,0 +1,248 @@ |
|||||
|
Metadata-Version: 2.1 |
||||
|
Name: asgiref |
||||
|
Version: 3.5.0 |
||||
|
Summary: ASGI specs, helper code, and adapters |
||||
|
Home-page: https://github.com/django/asgiref/ |
||||
|
Author: Django Software Foundation |
||||
|
Author-email: foundation@djangoproject.com |
||||
|
License: BSD |
||||
|
Project-URL: Documentation, https://asgi.readthedocs.io/ |
||||
|
Project-URL: Further Documentation, https://docs.djangoproject.com/en/stable/topics/async/#async-adapter-functions |
||||
|
Project-URL: Changelog, https://github.com/django/asgiref/blob/master/CHANGELOG.txt |
||||
|
Platform: UNKNOWN |
||||
|
Classifier: Development Status :: 5 - Production/Stable |
||||
|
Classifier: Environment :: Web Environment |
||||
|
Classifier: Intended Audience :: Developers |
||||
|
Classifier: License :: OSI Approved :: BSD License |
||||
|
Classifier: Operating System :: OS Independent |
||||
|
Classifier: Programming Language :: Python |
||||
|
Classifier: Programming Language :: Python :: 3 |
||||
|
Classifier: Programming Language :: Python :: 3 :: Only |
||||
|
Classifier: Programming Language :: Python :: 3.7 |
||||
|
Classifier: Programming Language :: Python :: 3.8 |
||||
|
Classifier: Programming Language :: Python :: 3.9 |
||||
|
Classifier: Programming Language :: Python :: 3.10 |
||||
|
Classifier: Topic :: Internet :: WWW/HTTP |
||||
|
Requires-Python: >=3.7 |
||||
|
License-File: LICENSE |
||||
|
Requires-Dist: typing-extensions ; python_version < "3.8" |
||||
|
Provides-Extra: tests |
||||
|
Requires-Dist: pytest ; extra == 'tests' |
||||
|
Requires-Dist: pytest-asyncio ; extra == 'tests' |
||||
|
Requires-Dist: mypy (>=0.800) ; extra == 'tests' |
||||
|
|
||||
|
asgiref |
||||
|
======= |
||||
|
|
||||
|
.. image:: https://api.travis-ci.org/django/asgiref.svg |
||||
|
:target: https://travis-ci.org/django/asgiref |
||||
|
|
||||
|
.. image:: https://img.shields.io/pypi/v/asgiref.svg |
||||
|
:target: https://pypi.python.org/pypi/asgiref |
||||
|
|
||||
|
ASGI is a standard for Python asynchronous web apps and servers to communicate |
||||
|
with each other, and positioned as an asynchronous successor to WSGI. You can |
||||
|
read more at https://asgi.readthedocs.io/en/latest/ |
||||
|
|
||||
|
This package includes ASGI base libraries, such as: |
||||
|
|
||||
|
* Sync-to-async and async-to-sync function wrappers, ``asgiref.sync`` |
||||
|
* Server base classes, ``asgiref.server`` |
||||
|
* A WSGI-to-ASGI adapter, in ``asgiref.wsgi`` |
||||
|
|
||||
|
|
||||
|
Function wrappers |
||||
|
----------------- |
||||
|
|
||||
|
These allow you to wrap or decorate async or sync functions to call them from |
||||
|
the other style (so you can call async functions from a synchronous thread, |
||||
|
or vice-versa). |
||||
|
|
||||
|
In particular: |
||||
|
|
||||
|
* AsyncToSync lets a synchronous subthread stop and wait while the async |
||||
|
function is called on the main thread's event loop, and then control is |
||||
|
returned to the thread when the async function is finished. |
||||
|
|
||||
|
* SyncToAsync lets async code call a synchronous function, which is run in |
||||
|
a threadpool and control returned to the async coroutine when the synchronous |
||||
|
function completes. |
||||
|
|
||||
|
The idea is to make it easier to call synchronous APIs from async code and |
||||
|
asynchronous APIs from synchronous code so it's easier to transition code from |
||||
|
one style to the other. In the case of Channels, we wrap the (synchronous) |
||||
|
Django view system with SyncToAsync to allow it to run inside the (asynchronous) |
||||
|
ASGI server. |
||||
|
|
||||
|
Note that exactly what threads things run in is very specific, and aimed to |
||||
|
keep maximum compatibility with old synchronous code. See |
||||
|
"Synchronous code & Threads" below for a full explanation. By default, |
||||
|
``sync_to_async`` will run all synchronous code in the program in the same |
||||
|
thread for safety reasons; you can disable this for more performance with |
||||
|
``@sync_to_async(thread_sensitive=False)``, but make sure that your code does |
||||
|
not rely on anything bound to threads (like database connections) when you do. |
||||
|
|
||||
|
|
||||
|
Threadlocal replacement |
||||
|
----------------------- |
||||
|
|
||||
|
This is a drop-in replacement for ``threading.local`` that works with both |
||||
|
threads and asyncio Tasks. Even better, it will proxy values through from a |
||||
|
task-local context to a thread-local context when you use ``sync_to_async`` |
||||
|
to run things in a threadpool, and vice-versa for ``async_to_sync``. |
||||
|
|
||||
|
If you instead want true thread- and task-safety, you can set |
||||
|
``thread_critical`` on the Local object to ensure this instead. |
||||
|
|
||||
|
|
||||
|
Server base classes |
||||
|
------------------- |
||||
|
|
||||
|
Includes a ``StatelessServer`` class which provides all the hard work of |
||||
|
writing a stateless server (as in, does not handle direct incoming sockets |
||||
|
but instead consumes external streams or sockets to work out what is happening). |
||||
|
|
||||
|
An example of such a server would be a chatbot server that connects out to |
||||
|
a central chat server and provides a "connection scope" per user chatting to |
||||
|
it. There's only one actual connection, but the server has to separate things |
||||
|
into several scopes for easier writing of the code. |
||||
|
|
||||
|
You can see an example of this being used in `frequensgi <https://github.com/andrewgodwin/frequensgi>`_. |
||||
|
|
||||
|
|
||||
|
WSGI-to-ASGI adapter |
||||
|
-------------------- |
||||
|
|
||||
|
Allows you to wrap a WSGI application so it appears as a valid ASGI application. |
||||
|
|
||||
|
Simply wrap it around your WSGI application like so:: |
||||
|
|
||||
|
asgi_application = WsgiToAsgi(wsgi_application) |
||||
|
|
||||
|
The WSGI application will be run in a synchronous threadpool, and the wrapped |
||||
|
ASGI application will be one that accepts ``http`` class messages. |
||||
|
|
||||
|
Please note that not all extended features of WSGI may be supported (such as |
||||
|
file handles for incoming POST bodies). |
||||
|
|
||||
|
|
||||
|
Dependencies |
||||
|
------------ |
||||
|
|
||||
|
``asgiref`` requires Python 3.7 or higher. |
||||
|
|
||||
|
|
||||
|
Contributing |
||||
|
------------ |
||||
|
|
||||
|
Please refer to the |
||||
|
`main Channels contributing docs <https://github.com/django/channels/blob/master/CONTRIBUTING.rst>`_. |
||||
|
|
||||
|
|
||||
|
Testing |
||||
|
''''''' |
||||
|
|
||||
|
To run tests, make sure you have installed the ``tests`` extra with the package:: |
||||
|
|
||||
|
cd asgiref/ |
||||
|
pip install -e .[tests] |
||||
|
pytest |
||||
|
|
||||
|
|
||||
|
Building the documentation |
||||
|
'''''''''''''''''''''''''' |
||||
|
|
||||
|
The documentation uses `Sphinx <http://www.sphinx-doc.org>`_:: |
||||
|
|
||||
|
cd asgiref/docs/ |
||||
|
pip install sphinx |
||||
|
|
||||
|
To build the docs, you can use the default tools:: |
||||
|
|
||||
|
sphinx-build -b html . _build/html # or `make html`, if you've got make set up |
||||
|
cd _build/html |
||||
|
python -m http.server |
||||
|
|
||||
|
...or you can use ``sphinx-autobuild`` to run a server and rebuild/reload |
||||
|
your documentation changes automatically:: |
||||
|
|
||||
|
pip install sphinx-autobuild |
||||
|
sphinx-autobuild . _build/html |
||||
|
|
||||
|
|
||||
|
Releasing |
||||
|
''''''''' |
||||
|
|
||||
|
To release, first add details to CHANGELOG.txt and update the version number in ``asgiref/__init__.py``. |
||||
|
|
||||
|
Then, build and push the packages:: |
||||
|
|
||||
|
python -m build |
||||
|
twine upload dist/* |
||||
|
rm -r build/ dist/ |
||||
|
|
||||
|
|
||||
|
Implementation Details |
||||
|
---------------------- |
||||
|
|
||||
|
Synchronous code & threads |
||||
|
'''''''''''''''''''''''''' |
||||
|
|
||||
|
The ``asgiref.sync`` module provides two wrappers that let you go between |
||||
|
asynchronous and synchronous code at will, while taking care of the rough edges |
||||
|
for you. |
||||
|
|
||||
|
Unfortunately, the rough edges are numerous, and the code has to work especially |
||||
|
hard to keep things in the same thread as much as possible. Notably, the |
||||
|
restrictions we are working with are: |
||||
|
|
||||
|
* All synchronous code called through ``SyncToAsync`` and marked with |
||||
|
``thread_sensitive`` should run in the same thread as each other (and if the |
||||
|
outer layer of the program is synchronous, the main thread) |
||||
|
|
||||
|
* If a thread already has a running async loop, ``AsyncToSync`` can't run things |
||||
|
on that loop if it's blocked on synchronous code that is above you in the |
||||
|
call stack. |
||||
|
|
||||
|
The first compromise you get to might be that ``thread_sensitive`` code should |
||||
|
just run in the same thread and not spawn in a sub-thread, fulfilling the first |
||||
|
restriction, but that immediately runs you into the second restriction. |
||||
|
|
||||
|
The only real solution is to essentially have a variant of ThreadPoolExecutor |
||||
|
that executes any ``thread_sensitive`` code on the outermost synchronous |
||||
|
thread - either the main thread, or a single spawned subthread. |
||||
|
|
||||
|
This means you now have two basic states: |
||||
|
|
||||
|
* If the outermost layer of your program is synchronous, then all async code |
||||
|
run through ``AsyncToSync`` will run in a per-call event loop in arbitrary |
||||
|
sub-threads, while all ``thread_sensitive`` code will run in the main thread. |
||||
|
|
||||
|
* If the outermost layer of your program is asynchronous, then all async code |
||||
|
runs on the main thread's event loop, and all ``thread_sensitive`` synchronous |
||||
|
code will run in a single shared sub-thread. |
||||
|
|
||||
|
Crucially, this means that in both cases there is a thread which is a shared |
||||
|
resource that all ``thread_sensitive`` code must run on, and there is a chance |
||||
|
that this thread is currently blocked on its own ``AsyncToSync`` call. Thus, |
||||
|
``AsyncToSync`` needs to act as an executor for thread code while it's blocking. |
||||
|
|
||||
|
The ``CurrentThreadExecutor`` class provides this functionality; rather than |
||||
|
simply waiting on a Future, you can call its ``run_until_future`` method and |
||||
|
it will run submitted code until that Future is done. This means that code |
||||
|
inside the call can then run code on your thread. |
||||
|
|
||||
|
|
||||
|
Maintenance and Security |
||||
|
------------------------ |
||||
|
|
||||
|
To report security issues, please contact security@djangoproject.com. For GPG |
||||
|
signatures and more security process information, see |
||||
|
https://docs.djangoproject.com/en/dev/internals/security/. |
||||
|
|
||||
|
To report bugs or request new features, please open a new GitHub issue. |
||||
|
|
||||
|
This repository is part of the Channels project. For the shepherd and maintenance team, please see the |
||||
|
`main Channels readme <https://github.com/django/channels/blob/master/README.rst>`_. |
||||
|
|
||||
|
|
@ -0,0 +1,27 @@ |
|||||
|
asgiref-3.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 |
||||
|
asgiref-3.5.0.dist-info/LICENSE,sha256=uEZBXRtRTpwd_xSiLeuQbXlLxUbKYSn5UKGM0JHipmk,1552 |
||||
|
asgiref-3.5.0.dist-info/METADATA,sha256=bMkU821Y4ssj34LYK6R1ytLYcpXhqagXszRtAentodE,9163 |
||||
|
asgiref-3.5.0.dist-info/RECORD,, |
||||
|
asgiref-3.5.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 |
||||
|
asgiref-3.5.0.dist-info/top_level.txt,sha256=bokQjCzwwERhdBiPdvYEZa4cHxT4NCeAffQNUqJ8ssg,8 |
||||
|
asgiref/__init__.py,sha256=j0HWOe68EJbDKQHKURp6LgON8HyoWHbKmvvCvTB1OzA,22 |
||||
|
asgiref/__pycache__/__init__.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/compatibility.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/current_thread_executor.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/local.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/server.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/sync.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/testing.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/timeout.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/typing.cpython-39.pyc,, |
||||
|
asgiref/__pycache__/wsgi.cpython-39.pyc,, |
||||
|
asgiref/compatibility.py,sha256=MVH2bEdiCMMVTLbE-1V6KiU7q4LwqzP7PIufeXa-njM,1598 |
||||
|
asgiref/current_thread_executor.py,sha256=oeH8zv2tTmcbpxdUmOSMzbEXzeY5nJzIMFvzprE95gA,2801 |
||||
|
asgiref/local.py,sha256=nx5RqVFLYgUJVaxzApuQUW7dd9y21sruMYdgISoRs1k,4854 |
||||
|
asgiref/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 |
||||
|
asgiref/server.py,sha256=egTQhZo1k4G0F7SSBQNp_VOekpGcjBJZU2kkCoiGC_M,6005 |
||||
|
asgiref/sync.py,sha256=ugODYuUwixVJ1kYXzPQzMvDBQnSHd9h2dHo-CSZ5I0E,19304 |
||||
|
asgiref/testing.py,sha256=3byNRV7Oto_Fg8Z-fErQJ3yGf7OQlcUexbN_cDQugzQ,3119 |
||||
|
asgiref/timeout.py,sha256=5Ekbmn3X1HPR55qgx-hPJMPEu_-YoivHqNhFEitiSYE,3440 |
||||
|
asgiref/typing.py,sha256=MZ7vbJY1F7EQqo9gL9pMSFRMw9b_SQrQQsnvlJQ2iP4,5603 |
||||
|
asgiref/wsgi.py,sha256=-L0eo_uK_dq7EPjv1meW1BRGytURaO9NPESxnJc9CtA,6575 |
@ -0,0 +1,5 @@ |
|||||
|
Wheel-Version: 1.0 |
||||
|
Generator: bdist_wheel (0.37.1) |
||||
|
Root-Is-Purelib: true |
||||
|
Tag: py3-none-any |
||||
|
|
@ -0,0 +1 @@ |
|||||
|
asgiref |
@ -0,0 +1 @@ |
|||||
|
__version__ = "3.5.0" |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,47 @@ |
|||||
|
import asyncio |
||||
|
import inspect |
||||
|
|
||||
|
|
||||
|
def is_double_callable(application): |
||||
|
""" |
||||
|
Tests to see if an application is a legacy-style (double-callable) application. |
||||
|
""" |
||||
|
# Look for a hint on the object first |
||||
|
if getattr(application, "_asgi_single_callable", False): |
||||
|
return False |
||||
|
if getattr(application, "_asgi_double_callable", False): |
||||
|
return True |
||||
|
# Uninstanted classes are double-callable |
||||
|
if inspect.isclass(application): |
||||
|
return True |
||||
|
# Instanted classes depend on their __call__ |
||||
|
if hasattr(application, "__call__"): |
||||
|
# We only check to see if its __call__ is a coroutine function - |
||||
|
# if it's not, it still might be a coroutine function itself. |
||||
|
if asyncio.iscoroutinefunction(application.__call__): |
||||
|
return False |
||||
|
# Non-classes we just check directly |
||||
|
return not asyncio.iscoroutinefunction(application) |
||||
|
|
||||
|
|
||||
|
def double_to_single_callable(application): |
||||
|
""" |
||||
|
Transforms a double-callable ASGI application into a single-callable one. |
||||
|
""" |
||||
|
|
||||
|
async def new_application(scope, receive, send): |
||||
|
instance = application(scope) |
||||
|
return await instance(receive, send) |
||||
|
|
||||
|
return new_application |
||||
|
|
||||
|
|
||||
|
def guarantee_single_callable(application): |
||||
|
""" |
||||
|
Takes either a single- or double-callable application and always returns it |
||||
|
in single-callable style. Use this to add backwards compatibility for ASGI |
||||
|
2.0 applications to your server/test harness/etc. |
||||
|
""" |
||||
|
if is_double_callable(application): |
||||
|
application = double_to_single_callable(application) |
||||
|
return application |
@ -0,0 +1,81 @@ |
|||||
|
import queue |
||||
|
import threading |
||||
|
from concurrent.futures import Executor, Future |
||||
|
|
||||
|
|
||||
|
class _WorkItem: |
||||
|
""" |
||||
|
Represents an item needing to be run in the executor. |
||||
|
Copied from ThreadPoolExecutor (but it's private, so we're not going to rely on importing it) |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, future, fn, args, kwargs): |
||||
|
self.future = future |
||||
|
self.fn = fn |
||||
|
self.args = args |
||||
|
self.kwargs = kwargs |
||||
|
|
||||
|
def run(self): |
||||
|
if not self.future.set_running_or_notify_cancel(): |
||||
|
return |
||||
|
try: |
||||
|
result = self.fn(*self.args, **self.kwargs) |
||||
|
except BaseException as exc: |
||||
|
self.future.set_exception(exc) |
||||
|
# Break a reference cycle with the exception 'exc' |
||||
|
self = None |
||||
|
else: |
||||
|
self.future.set_result(result) |
||||
|
|
||||
|
|
||||
|
class CurrentThreadExecutor(Executor): |
||||
|
""" |
||||
|
An Executor that actually runs code in the thread it is instantiated in. |
||||
|
Passed to other threads running async code, so they can run sync code in |
||||
|
the thread they came from. |
||||
|
""" |
||||
|
|
||||
|
def __init__(self): |
||||
|
self._work_thread = threading.current_thread() |
||||
|
self._work_queue = queue.Queue() |
||||
|
self._broken = False |
||||
|
|
||||
|
def run_until_future(self, future): |
||||
|
""" |
||||
|
Runs the code in the work queue until a result is available from the future. |
||||
|
Should be run from the thread the executor is initialised in. |
||||
|
""" |
||||
|
# Check we're in the right thread |
||||
|
if threading.current_thread() != self._work_thread: |
||||
|
raise RuntimeError( |
||||
|
"You cannot run CurrentThreadExecutor from a different thread" |
||||
|
) |
||||
|
future.add_done_callback(self._work_queue.put) |
||||
|
# Keep getting and running work items until we get the future we're waiting for |
||||
|
# back via the future's done callback. |
||||
|
try: |
||||
|
while True: |
||||
|
# Get a work item and run it |
||||
|
work_item = self._work_queue.get() |
||||
|
if work_item is future: |
||||
|
return |
||||
|
work_item.run() |
||||
|
del work_item |
||||
|
finally: |
||||
|
self._broken = True |
||||
|
|
||||
|
def submit(self, fn, *args, **kwargs): |
||||
|
# Check they're not submitting from the same thread |
||||
|
if threading.current_thread() == self._work_thread: |
||||
|
raise RuntimeError( |
||||
|
"You cannot submit onto CurrentThreadExecutor from its own thread" |
||||
|
) |
||||
|
# Check they're not too late or the executor errored |
||||
|
if self._broken: |
||||
|
raise RuntimeError("CurrentThreadExecutor already quit or is broken") |
||||
|
# Add to work queue |
||||
|
f = Future() |
||||
|
work_item = _WorkItem(f, fn, args, kwargs) |
||||
|
self._work_queue.put(work_item) |
||||
|
# Return the future |
||||
|
return f |
@ -0,0 +1,120 @@ |
|||||
|
import random |
||||
|
import string |
||||
|
import sys |
||||
|
import threading |
||||
|
import weakref |
||||
|
|
||||
|
|
||||
|
class Local: |
||||
|
""" |
||||
|
A drop-in replacement for threading.locals that also works with asyncio |
||||
|
Tasks (via the current_task asyncio method), and passes locals through |
||||
|
sync_to_async and async_to_sync. |
||||
|
|
||||
|
Specifically: |
||||
|
- Locals work per-coroutine on any thread not spawned using asgiref |
||||
|
- Locals work per-thread on any thread not spawned using asgiref |
||||
|
- Locals are shared with the parent coroutine when using sync_to_async |
||||
|
- Locals are shared with the parent thread when using async_to_sync |
||||
|
(and if that thread was launched using sync_to_async, with its parent |
||||
|
coroutine as well, with this working for indefinite levels of nesting) |
||||
|
|
||||
|
Set thread_critical to True to not allow locals to pass from an async Task |
||||
|
to a thread it spawns. This is needed for code that truly needs |
||||
|
thread-safety, as opposed to things used for helpful context (e.g. sqlite |
||||
|
does not like being called from a different thread to the one it is from). |
||||
|
Thread-critical code will still be differentiated per-Task within a thread |
||||
|
as it is expected it does not like concurrent access. |
||||
|
|
||||
|
This doesn't use contextvars as it needs to support 3.6. Once it can support |
||||
|
3.7 only, we can then reimplement the storage more nicely. |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, thread_critical: bool = False) -> None: |
||||
|
self._thread_critical = thread_critical |
||||
|
self._thread_lock = threading.RLock() |
||||
|
self._context_refs: "weakref.WeakSet[object]" = weakref.WeakSet() |
||||
|
# Random suffixes stop accidental reuse between different Locals, |
||||
|
# though we try to force deletion as well. |
||||
|
self._attr_name = "_asgiref_local_impl_{}_{}".format( |
||||
|
id(self), |
||||
|
"".join(random.choice(string.ascii_letters) for i in range(8)), |
||||
|
) |
||||
|
|
||||
|
def _get_context_id(self): |
||||
|
""" |
||||
|
Get the ID we should use for looking up variables |
||||
|
""" |
||||
|
# Prevent a circular reference |
||||
|
from .sync import AsyncToSync, SyncToAsync |
||||
|
|
||||
|
# First, pull the current task if we can |
||||
|
context_id = SyncToAsync.get_current_task() |
||||
|
context_is_async = True |
||||
|
# OK, let's try for a thread ID |
||||
|
if context_id is None: |
||||
|
context_id = threading.current_thread() |
||||
|
context_is_async = False |
||||
|
# If we're thread-critical, we stop here, as we can't share contexts. |
||||
|
if self._thread_critical: |
||||
|
return context_id |
||||
|
# Now, take those and see if we can resolve them through the launch maps |
||||
|
for i in range(sys.getrecursionlimit()): |
||||
|
try: |
||||
|
if context_is_async: |
||||
|
# Tasks have a source thread in AsyncToSync |
||||
|
context_id = AsyncToSync.launch_map[context_id] |
||||
|
context_is_async = False |
||||
|
else: |
||||
|
# Threads have a source task in SyncToAsync |
||||
|
context_id = SyncToAsync.launch_map[context_id] |
||||
|
context_is_async = True |
||||
|
except KeyError: |
||||
|
break |
||||
|
else: |
||||
|
# Catch infinite loops (they happen if you are screwing around |
||||
|
# with AsyncToSync implementations) |
||||
|
raise RuntimeError("Infinite launch_map loops") |
||||
|
return context_id |
||||
|
|
||||
|
def _get_storage(self): |
||||
|
context_obj = self._get_context_id() |
||||
|
if not hasattr(context_obj, self._attr_name): |
||||
|
setattr(context_obj, self._attr_name, {}) |
||||
|
self._context_refs.add(context_obj) |
||||
|
return getattr(context_obj, self._attr_name) |
||||
|
|
||||
|
def __del__(self): |
||||
|
try: |
||||
|
for context_obj in self._context_refs: |
||||
|
try: |
||||
|
delattr(context_obj, self._attr_name) |
||||
|
except AttributeError: |
||||
|
pass |
||||
|
except TypeError: |
||||
|
# WeakSet.__iter__ can crash when interpreter is shutting down due |
||||
|
# to _IterationGuard being None. |
||||
|
pass |
||||
|
|
||||
|
def __getattr__(self, key): |
||||
|
with self._thread_lock: |
||||
|
storage = self._get_storage() |
||||
|
if key in storage: |
||||
|
return storage[key] |
||||
|
else: |
||||
|
raise AttributeError(f"{self!r} object has no attribute {key!r}") |
||||
|
|
||||
|
def __setattr__(self, key, value): |
||||
|
if key in ("_context_refs", "_thread_critical", "_thread_lock", "_attr_name"): |
||||
|
return super().__setattr__(key, value) |
||||
|
with self._thread_lock: |
||||
|
storage = self._get_storage() |
||||
|
storage[key] = value |
||||
|
|
||||
|
def __delattr__(self, key): |
||||
|
with self._thread_lock: |
||||
|
storage = self._get_storage() |
||||
|
if key in storage: |
||||
|
del storage[key] |
||||
|
else: |
||||
|
raise AttributeError(f"{self!r} object has no attribute {key!r}") |
@ -0,0 +1,157 @@ |
|||||
|
import asyncio |
||||
|
import logging |
||||
|
import time |
||||
|
import traceback |
||||
|
|
||||
|
from .compatibility import guarantee_single_callable |
||||
|
|
||||
|
logger = logging.getLogger(__name__) |
||||
|
|
||||
|
|
||||
|
class StatelessServer: |
||||
|
""" |
||||
|
Base server class that handles basic concepts like application instance |
||||
|
creation/pooling, exception handling, and similar, for stateless protocols |
||||
|
(i.e. ones without actual incoming connections to the process) |
||||
|
|
||||
|
Your code should override the handle() method, doing whatever it needs to, |
||||
|
and calling get_or_create_application_instance with a unique `scope_id` |
||||
|
and `scope` for the scope it wants to get. |
||||
|
|
||||
|
If an application instance is found with the same `scope_id`, you are |
||||
|
given its input queue, otherwise one is made for you with the scope provided |
||||
|
and you are given that fresh new input queue. Either way, you should do |
||||
|
something like: |
||||
|
|
||||
|
input_queue = self.get_or_create_application_instance( |
||||
|
"user-123456", |
||||
|
{"type": "testprotocol", "user_id": "123456", "username": "andrew"}, |
||||
|
) |
||||
|
input_queue.put_nowait(message) |
||||
|
|
||||
|
If you try and create an application instance and there are already |
||||
|
`max_application` instances, the oldest/least recently used one will be |
||||
|
reclaimed and shut down to make space. |
||||
|
|
||||
|
Application coroutines that error will be found periodically (every 100ms |
||||
|
by default) and have their exceptions printed to the console. Override |
||||
|
application_exception() if you want to do more when this happens. |
||||
|
|
||||
|
If you override run(), make sure you handle things like launching the |
||||
|
application checker. |
||||
|
""" |
||||
|
|
||||
|
application_checker_interval = 0.1 |
||||
|
|
||||
|
def __init__(self, application, max_applications=1000): |
||||
|
# Parameters |
||||
|
self.application = application |
||||
|
self.max_applications = max_applications |
||||
|
# Initialisation |
||||
|
self.application_instances = {} |
||||
|
|
||||
|
### Mainloop and handling |
||||
|
|
||||
|
def run(self): |
||||
|
""" |
||||
|
Runs the asyncio event loop with our handler loop. |
||||
|
""" |
||||
|
event_loop = asyncio.get_event_loop() |
||||
|
asyncio.ensure_future(self.application_checker()) |
||||
|
try: |
||||
|
event_loop.run_until_complete(self.handle()) |
||||
|
except KeyboardInterrupt: |
||||
|
logger.info("Exiting due to Ctrl-C/interrupt") |
||||
|
|
||||
|
async def handle(self): |
||||
|
raise NotImplementedError("You must implement handle()") |
||||
|
|
||||
|
async def application_send(self, scope, message): |
||||
|
""" |
||||
|
Receives outbound sends from applications and handles them. |
||||
|
""" |
||||
|
raise NotImplementedError("You must implement application_send()") |
||||
|
|
||||
|
### Application instance management |
||||
|
|
||||
|
def get_or_create_application_instance(self, scope_id, scope): |
||||
|
""" |
||||
|
Creates an application instance and returns its queue. |
||||
|
""" |
||||
|
if scope_id in self.application_instances: |
||||
|
self.application_instances[scope_id]["last_used"] = time.time() |
||||
|
return self.application_instances[scope_id]["input_queue"] |
||||
|
# See if we need to delete an old one |
||||
|
while len(self.application_instances) > self.max_applications: |
||||
|
self.delete_oldest_application_instance() |
||||
|
# Make an instance of the application |
||||
|
input_queue = asyncio.Queue() |
||||
|
application_instance = guarantee_single_callable(self.application) |
||||
|
# Run it, and stash the future for later checking |
||||
|
future = asyncio.ensure_future( |
||||
|
application_instance( |
||||
|
scope=scope, |
||||
|
receive=input_queue.get, |
||||
|
send=lambda message: self.application_send(scope, message), |
||||
|
), |
||||
|
) |
||||
|
self.application_instances[scope_id] = { |
||||
|
"input_queue": input_queue, |
||||
|
"future": future, |
||||
|
"scope": scope, |
||||
|
"last_used": time.time(), |
||||
|
} |
||||
|
return input_queue |
||||
|
|
||||
|
def delete_oldest_application_instance(self): |
||||
|
""" |
||||
|
Finds and deletes the oldest application instance |
||||
|
""" |
||||
|
oldest_time = min( |
||||
|
details["last_used"] for details in self.application_instances.values() |
||||
|
) |
||||
|
for scope_id, details in self.application_instances.items(): |
||||
|
if details["last_used"] == oldest_time: |
||||
|
self.delete_application_instance(scope_id) |
||||
|
# Return to make sure we only delete one in case two have |
||||
|
# the same oldest time |
||||
|
return |
||||
|
|
||||
|
def delete_application_instance(self, scope_id): |
||||
|
""" |
||||
|
Removes an application instance (makes sure its task is stopped, |
||||
|
then removes it from the current set) |
||||
|
""" |
||||
|
details = self.application_instances[scope_id] |
||||
|
del self.application_instances[scope_id] |
||||
|
if not details["future"].done(): |
||||
|
details["future"].cancel() |
||||
|
|
||||
|
async def application_checker(self): |
||||
|
""" |
||||
|
Goes through the set of current application instance Futures and cleans up |
||||
|
any that are done/prints exceptions for any that errored. |
||||
|
""" |
||||
|
while True: |
||||
|
await asyncio.sleep(self.application_checker_interval) |
||||
|
for scope_id, details in list(self.application_instances.items()): |
||||
|
if details["future"].done(): |
||||
|
exception = details["future"].exception() |
||||
|
if exception: |
||||
|
await self.application_exception(exception, details) |
||||
|
try: |
||||
|
del self.application_instances[scope_id] |
||||
|
except KeyError: |
||||
|
# Exception handling might have already got here before us. That's fine. |
||||
|
pass |
||||
|
|
||||
|
async def application_exception(self, exception, application_details): |
||||
|
""" |
||||
|
Called whenever an application coroutine has an exception. |
||||
|
""" |
||||
|
logging.error( |
||||
|
"Exception inside application: %s\n%s%s", |
||||
|
exception, |
||||
|
"".join(traceback.format_tb(exception.__traceback__)), |
||||
|
f" {exception}", |
||||
|
) |
@ -0,0 +1,511 @@ |
|||||
|
import asyncio.coroutines |
||||
|
import contextvars |
||||
|
import functools |
||||
|
import inspect |
||||
|
import os |
||||
|
import sys |
||||
|
import threading |
||||
|
import warnings |
||||
|
import weakref |
||||
|
from concurrent.futures import Future, ThreadPoolExecutor |
||||
|
from typing import Any, Callable, Dict, Optional, overload |
||||
|
|
||||
|
from .current_thread_executor import CurrentThreadExecutor |
||||
|
from .local import Local |
||||
|
|
||||
|
|
||||
|
def _restore_context(context): |
||||
|
# Check for changes in contextvars, and set them to the current |
||||
|
# context for downstream consumers |
||||
|
for cvar in context: |
||||
|
try: |
||||
|
if cvar.get() != context.get(cvar): |
||||
|
cvar.set(context.get(cvar)) |
||||
|
except LookupError: |
||||
|
cvar.set(context.get(cvar)) |
||||
|
|
||||
|
|
||||
|
def _iscoroutinefunction_or_partial(func: Any) -> bool: |
||||
|
# Python < 3.8 does not correctly determine partially wrapped |
||||
|
# coroutine functions are coroutine functions, hence the need for |
||||
|
# this to exist. Code taken from CPython. |
||||
|
if sys.version_info >= (3, 8): |
||||
|
return asyncio.iscoroutinefunction(func) |
||||
|
else: |
||||
|
while inspect.ismethod(func): |
||||
|
func = func.__func__ |
||||
|
while isinstance(func, functools.partial): |
||||
|
func = func.func |
||||
|
|
||||
|
return asyncio.iscoroutinefunction(func) |
||||
|
|
||||
|
|
||||
|
class ThreadSensitiveContext: |
||||
|
"""Async context manager to manage context for thread sensitive mode |
||||
|
|
||||
|
This context manager controls which thread pool executor is used when in |
||||
|
thread sensitive mode. By default, a single thread pool executor is shared |
||||
|
within a process. |
||||
|
|
||||
|
In Python 3.7+, the ThreadSensitiveContext() context manager may be used to |
||||
|
specify a thread pool per context. |
||||
|
|
||||
|
This context manager is re-entrant, so only the outer-most call to |
||||
|
ThreadSensitiveContext will set the context. |
||||
|
|
||||
|
Usage: |
||||
|
|
||||
|
>>> import time |
||||
|
>>> async with ThreadSensitiveContext(): |
||||
|
... await sync_to_async(time.sleep, 1)() |
||||
|
""" |
||||
|
|
||||
|
def __init__(self): |
||||
|
self.token = None |
||||
|
|
||||
|
async def __aenter__(self): |
||||
|
try: |
||||
|
SyncToAsync.thread_sensitive_context.get() |
||||
|
except LookupError: |
||||
|
self.token = SyncToAsync.thread_sensitive_context.set(self) |
||||
|
|
||||
|
return self |
||||
|
|
||||
|
async def __aexit__(self, exc, value, tb): |
||||
|
if not self.token: |
||||
|
return |
||||
|
|
||||
|
executor = SyncToAsync.context_to_thread_executor.pop(self, None) |
||||
|
if executor: |
||||
|
executor.shutdown() |
||||
|
SyncToAsync.thread_sensitive_context.reset(self.token) |
||||
|
|
||||
|
|
||||
|
class AsyncToSync: |
||||
|
""" |
||||
|
Utility class which turns an awaitable that only works on the thread with |
||||
|
the event loop into a synchronous callable that works in a subthread. |
||||
|
|
||||
|
If the call stack contains an async loop, the code runs there. |
||||
|
Otherwise, the code runs in a new loop in a new thread. |
||||
|
|
||||
|
Either way, this thread then pauses and waits to run any thread_sensitive |
||||
|
code called from further down the call stack using SyncToAsync, before |
||||
|
finally exiting once the async task returns. |
||||
|
""" |
||||
|
|
||||
|
# Maps launched Tasks to the threads that launched them (for locals impl) |
||||
|
launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} |
||||
|
|
||||
|
# Keeps track of which CurrentThreadExecutor to use. This uses an asgiref |
||||
|
# Local, not a threadlocal, so that tasks can work out what their parent used. |
||||
|
executors = Local() |
||||
|
|
||||
|
def __init__(self, awaitable, force_new_loop=False): |
||||
|
if not callable(awaitable) or not _iscoroutinefunction_or_partial(awaitable): |
||||
|
# Python does not have very reliable detection of async functions |
||||
|
# (lots of false negatives) so this is just a warning. |
||||
|
warnings.warn( |
||||
|
"async_to_sync was passed a non-async-marked callable", stacklevel=2 |
||||
|
) |
||||
|
self.awaitable = awaitable |
||||
|
try: |
||||
|
self.__self__ = self.awaitable.__self__ |
||||
|
except AttributeError: |
||||
|
pass |
||||
|
if force_new_loop: |
||||
|
# They have asked that we always run in a new sub-loop. |
||||
|
self.main_event_loop = None |
||||
|
else: |
||||
|
try: |
||||
|
self.main_event_loop = asyncio.get_running_loop() |
||||
|
except RuntimeError: |
||||
|
# There's no event loop in this thread. Look for the threadlocal if |
||||
|
# we're inside SyncToAsync |
||||
|
main_event_loop_pid = getattr( |
||||
|
SyncToAsync.threadlocal, "main_event_loop_pid", None |
||||
|
) |
||||
|
# We make sure the parent loop is from the same process - if |
||||
|
# they've forked, this is not going to be valid any more (#194) |
||||
|
if main_event_loop_pid and main_event_loop_pid == os.getpid(): |
||||
|
self.main_event_loop = getattr( |
||||
|
SyncToAsync.threadlocal, "main_event_loop", None |
||||
|
) |
||||
|
else: |
||||
|
self.main_event_loop = None |
||||
|
|
||||
|
def __call__(self, *args, **kwargs): |
||||
|
# You can't call AsyncToSync from a thread with a running event loop |
||||
|
try: |
||||
|
event_loop = asyncio.get_running_loop() |
||||
|
except RuntimeError: |
||||
|
pass |
||||
|
else: |
||||
|
if event_loop.is_running(): |
||||
|
raise RuntimeError( |
||||
|
"You cannot use AsyncToSync in the same thread as an async event loop - " |
||||
|
"just await the async function directly." |
||||
|
) |
||||
|
|
||||
|
# Wrapping context in list so it can be reassigned from within |
||||
|
# `main_wrap`. |
||||
|
context = [contextvars.copy_context()] |
||||
|
|
||||
|
# Make a future for the return information |
||||
|
call_result = Future() |
||||
|
# Get the source thread |
||||
|
source_thread = threading.current_thread() |
||||
|
# Make a CurrentThreadExecutor we'll use to idle in this thread - we |
||||
|
# need one for every sync frame, even if there's one above us in the |
||||
|
# same thread. |
||||
|
if hasattr(self.executors, "current"): |
||||
|
old_current_executor = self.executors.current |
||||
|
else: |
||||
|
old_current_executor = None |
||||
|
current_executor = CurrentThreadExecutor() |
||||
|
self.executors.current = current_executor |
||||
|
# Use call_soon_threadsafe to schedule a synchronous callback on the |
||||
|
# main event loop's thread if it's there, otherwise make a new loop |
||||
|
# in this thread. |
||||
|
try: |
||||
|
awaitable = self.main_wrap( |
||||
|
args, kwargs, call_result, source_thread, sys.exc_info(), context |
||||
|
) |
||||
|
|
||||
|
if not (self.main_event_loop and self.main_event_loop.is_running()): |
||||
|
# Make our own event loop - in a new thread - and run inside that. |
||||
|
loop = asyncio.new_event_loop() |
||||
|
loop_executor = ThreadPoolExecutor(max_workers=1) |
||||
|
loop_future = loop_executor.submit( |
||||
|
self._run_event_loop, loop, awaitable |
||||
|
) |
||||
|
if current_executor: |
||||
|
# Run the CurrentThreadExecutor until the future is done |
||||
|
current_executor.run_until_future(loop_future) |
||||
|
# Wait for future and/or allow for exception propagation |
||||
|
loop_future.result() |
||||
|
else: |
||||
|
# Call it inside the existing loop |
||||
|
self.main_event_loop.call_soon_threadsafe( |
||||
|
self.main_event_loop.create_task, awaitable |
||||
|
) |
||||
|
if current_executor: |
||||
|
# Run the CurrentThreadExecutor until the future is done |
||||
|
current_executor.run_until_future(call_result) |
||||
|
finally: |
||||
|
# Clean up any executor we were running |
||||
|
if hasattr(self.executors, "current"): |
||||
|
del self.executors.current |
||||
|
if old_current_executor: |
||||
|
self.executors.current = old_current_executor |
||||
|
_restore_context(context[0]) |
||||
|
|
||||
|
# Wait for results from the future. |
||||
|
return call_result.result() |
||||
|
|
||||
|
def _run_event_loop(self, loop, coro): |
||||
|
""" |
||||
|
Runs the given event loop (designed to be called in a thread). |
||||
|
""" |
||||
|
asyncio.set_event_loop(loop) |
||||
|
try: |
||||
|
loop.run_until_complete(coro) |
||||
|
finally: |
||||
|
try: |
||||
|
# mimic asyncio.run() behavior |
||||
|
# cancel unexhausted async generators |
||||
|
tasks = asyncio.all_tasks(loop) |
||||
|
for task in tasks: |
||||
|
task.cancel() |
||||
|
|
||||
|
async def gather(): |
||||
|
await asyncio.gather(*tasks, return_exceptions=True) |
||||
|
|
||||
|
loop.run_until_complete(gather()) |
||||
|
for task in tasks: |
||||
|
if task.cancelled(): |
||||
|
continue |
||||
|
if task.exception() is not None: |
||||
|
loop.call_exception_handler( |
||||
|
{ |
||||
|
"message": "unhandled exception during loop shutdown", |
||||
|
"exception": task.exception(), |
||||
|
"task": task, |
||||
|
} |
||||
|
) |
||||
|
if hasattr(loop, "shutdown_asyncgens"): |
||||
|
loop.run_until_complete(loop.shutdown_asyncgens()) |
||||
|
finally: |
||||
|
loop.close() |
||||
|
asyncio.set_event_loop(self.main_event_loop) |
||||
|
|
||||
|
def __get__(self, parent, objtype): |
||||
|
""" |
||||
|
Include self for methods |
||||
|
""" |
||||
|
func = functools.partial(self.__call__, parent) |
||||
|
return functools.update_wrapper(func, self.awaitable) |
||||
|
|
||||
|
async def main_wrap( |
||||
|
self, args, kwargs, call_result, source_thread, exc_info, context |
||||
|
): |
||||
|
""" |
||||
|
Wraps the awaitable with something that puts the result into the |
||||
|
result/exception future. |
||||
|
""" |
||||
|
if context is not None: |
||||
|
_restore_context(context[0]) |
||||
|
|
||||
|
current_task = SyncToAsync.get_current_task() |
||||
|
self.launch_map[current_task] = source_thread |
||||
|
try: |
||||
|
# If we have an exception, run the function inside the except block |
||||
|
# after raising it so exc_info is correctly populated. |
||||
|
if exc_info[1]: |
||||
|
try: |
||||
|
raise exc_info[1] |
||||
|
except BaseException: |
||||
|
result = await self.awaitable(*args, **kwargs) |
||||
|
else: |
||||
|
result = await self.awaitable(*args, **kwargs) |
||||
|
except BaseException as e: |
||||
|
call_result.set_exception(e) |
||||
|
else: |
||||
|
call_result.set_result(result) |
||||
|
finally: |
||||
|
del self.launch_map[current_task] |
||||
|
|
||||
|
context[0] = contextvars.copy_context() |
||||
|
|
||||
|
|
||||
|
class SyncToAsync: |
||||
|
""" |
||||
|
Utility class which turns a synchronous callable into an awaitable that |
||||
|
runs in a threadpool. It also sets a threadlocal inside the thread so |
||||
|
calls to AsyncToSync can escape it. |
||||
|
|
||||
|
If thread_sensitive is passed, the code will run in the same thread as any |
||||
|
outer code. This is needed for underlying Python code that is not |
||||
|
threadsafe (for example, code which handles SQLite database connections). |
||||
|
|
||||
|
If the outermost program is async (i.e. SyncToAsync is outermost), then |
||||
|
this will be a dedicated single sub-thread that all sync code runs in, |
||||
|
one after the other. If the outermost program is sync (i.e. AsyncToSync is |
||||
|
outermost), this will just be the main thread. This is achieved by idling |
||||
|
with a CurrentThreadExecutor while AsyncToSync is blocking its sync parent, |
||||
|
rather than just blocking. |
||||
|
|
||||
|
If executor is passed in, that will be used instead of the loop's default executor. |
||||
|
In order to pass in an executor, thread_sensitive must be set to False, otherwise |
||||
|
a TypeError will be raised. |
||||
|
""" |
||||
|
|
||||
|
# If they've set ASGI_THREADS, update the default asyncio executor for now |
||||
|
if "ASGI_THREADS" in os.environ: |
||||
|
# We use get_event_loop here - not get_running_loop - as this will |
||||
|
# be run at import time, and we want to update the main thread's loop. |
||||
|
loop = asyncio.get_event_loop() |
||||
|
loop.set_default_executor( |
||||
|
ThreadPoolExecutor(max_workers=int(os.environ["ASGI_THREADS"])) |
||||
|
) |
||||
|
|
||||
|
# Maps launched threads to the coroutines that spawned them |
||||
|
launch_map: "Dict[threading.Thread, asyncio.Task[object]]" = {} |
||||
|
|
||||
|
# Storage for main event loop references |
||||
|
threadlocal = threading.local() |
||||
|
|
||||
|
# Single-thread executor for thread-sensitive code |
||||
|
single_thread_executor = ThreadPoolExecutor(max_workers=1) |
||||
|
|
||||
|
# Maintain a contextvar for the current execution context. Optionally used |
||||
|
# for thread sensitive mode. |
||||
|
thread_sensitive_context: "contextvars.ContextVar[str]" = contextvars.ContextVar( |
||||
|
"thread_sensitive_context" |
||||
|
) |
||||
|
|
||||
|
# Contextvar that is used to detect if the single thread executor |
||||
|
# would be awaited on while already being used in the same context |
||||
|
deadlock_context: "contextvars.ContextVar[bool]" = contextvars.ContextVar( |
||||
|
"deadlock_context" |
||||
|
) |
||||
|
|
||||
|
# Maintaining a weak reference to the context ensures that thread pools are |
||||
|
# erased once the context goes out of scope. This terminates the thread pool. |
||||
|
context_to_thread_executor: "weakref.WeakKeyDictionary[object, ThreadPoolExecutor]" = ( |
||||
|
weakref.WeakKeyDictionary() |
||||
|
) |
||||
|
|
||||
|
def __init__( |
||||
|
self, |
||||
|
func: Callable[..., Any], |
||||
|
thread_sensitive: bool = True, |
||||
|
executor: Optional["ThreadPoolExecutor"] = None, |
||||
|
) -> None: |
||||
|
if not callable(func) or _iscoroutinefunction_or_partial(func): |
||||
|
raise TypeError("sync_to_async can only be applied to sync functions.") |
||||
|
self.func = func |
||||
|
functools.update_wrapper(self, func) |
||||
|
self._thread_sensitive = thread_sensitive |
||||
|
self._is_coroutine = asyncio.coroutines._is_coroutine # type: ignore |
||||
|
if thread_sensitive and executor is not None: |
||||
|
raise TypeError("executor must not be set when thread_sensitive is True") |
||||
|
self._executor = executor |
||||
|
try: |
||||
|
self.__self__ = func.__self__ # type: ignore |
||||
|
except AttributeError: |
||||
|
pass |
||||
|
|
||||
|
async def __call__(self, *args, **kwargs): |
||||
|
loop = asyncio.get_running_loop() |
||||
|
|
||||
|
# Work out what thread to run the code in |
||||
|
if self._thread_sensitive: |
||||
|
if hasattr(AsyncToSync.executors, "current"): |
||||
|
# If we have a parent sync thread above somewhere, use that |
||||
|
executor = AsyncToSync.executors.current |
||||
|
elif self.thread_sensitive_context and self.thread_sensitive_context.get( |
||||
|
None |
||||
|
): |
||||
|
# If we have a way of retrieving the current context, attempt |
||||
|
# to use a per-context thread pool executor |
||||
|
thread_sensitive_context = self.thread_sensitive_context.get() |
||||
|
|
||||
|
if thread_sensitive_context in self.context_to_thread_executor: |
||||
|
# Re-use thread executor in current context |
||||
|
executor = self.context_to_thread_executor[thread_sensitive_context] |
||||
|
else: |
||||
|
# Create new thread executor in current context |
||||
|
executor = ThreadPoolExecutor(max_workers=1) |
||||
|
self.context_to_thread_executor[thread_sensitive_context] = executor |
||||
|
elif self.deadlock_context and self.deadlock_context.get(False): |
||||
|
raise RuntimeError( |
||||
|
"Single thread executor already being used, would deadlock" |
||||
|
) |
||||
|
else: |
||||
|
# Otherwise, we run it in a fixed single thread |
||||
|
executor = self.single_thread_executor |
||||
|
if self.deadlock_context: |
||||
|
self.deadlock_context.set(True) |
||||
|
else: |
||||
|
# Use the passed in executor, or the loop's default if it is None |
||||
|
executor = self._executor |
||||
|
|
||||
|
context = contextvars.copy_context() |
||||
|
child = functools.partial(self.func, *args, **kwargs) |
||||
|
func = context.run |
||||
|
args = (child,) |
||||
|
kwargs = {} |
||||
|
|
||||
|
try: |
||||
|
# Run the code in the right thread |
||||
|
future = loop.run_in_executor( |
||||
|
executor, |
||||
|
functools.partial( |
||||
|
self.thread_handler, |
||||
|
loop, |
||||
|
self.get_current_task(), |
||||
|
sys.exc_info(), |
||||
|
func, |
||||
|
*args, |
||||
|
**kwargs, |
||||
|
), |
||||
|
) |
||||
|
ret = await asyncio.wait_for(future, timeout=None) |
||||
|
|
||||
|
finally: |
||||
|
_restore_context(context) |
||||
|
if self.deadlock_context: |
||||
|
self.deadlock_context.set(False) |
||||
|
|
||||
|
return ret |
||||
|
|
||||
|
def __get__(self, parent, objtype): |
||||
|
""" |
||||
|
Include self for methods |
||||
|
""" |
||||
|
return functools.partial(self.__call__, parent) |
||||
|
|
||||
|
def thread_handler(self, loop, source_task, exc_info, func, *args, **kwargs): |
||||
|
""" |
||||
|
Wraps the sync application with exception handling. |
||||
|
""" |
||||
|
# Set the threadlocal for AsyncToSync |
||||
|
self.threadlocal.main_event_loop = loop |
||||
|
self.threadlocal.main_event_loop_pid = os.getpid() |
||||
|
# Set the task mapping (used for the locals module) |
||||
|
current_thread = threading.current_thread() |
||||
|
if AsyncToSync.launch_map.get(source_task) == current_thread: |
||||
|
# Our parent task was launched from this same thread, so don't make |
||||
|
# a launch map entry - let it shortcut over us! (and stop infinite loops) |
||||
|
parent_set = False |
||||
|
else: |
||||
|
self.launch_map[current_thread] = source_task |
||||
|
parent_set = True |
||||
|
# Run the function |
||||
|
try: |
||||
|
# If we have an exception, run the function inside the except block |
||||
|
# after raising it so exc_info is correctly populated. |
||||
|
if exc_info[1]: |
||||
|
try: |
||||
|
raise exc_info[1] |
||||
|
except BaseException: |
||||
|
return func(*args, **kwargs) |
||||
|
else: |
||||
|
return func(*args, **kwargs) |
||||
|
finally: |
||||
|
# Only delete the launch_map parent if we set it, otherwise it is |
||||
|
# from someone else. |
||||
|
if parent_set: |
||||
|
del self.launch_map[current_thread] |
||||
|
|
||||
|
@staticmethod |
||||
|
def get_current_task(): |
||||
|
""" |
||||
|
Implementation of asyncio.current_task() |
||||
|
that returns None if there is no task. |
||||
|
""" |
||||
|
try: |
||||
|
return asyncio.current_task() |
||||
|
except RuntimeError: |
||||
|
return None |
||||
|
|
||||
|
|
||||
|
# Lowercase aliases (and decorator friendliness) |
||||
|
async_to_sync = AsyncToSync |
||||
|
|
||||
|
|
||||
|
@overload |
||||
|
def sync_to_async( |
||||
|
func: None = None, |
||||
|
thread_sensitive: bool = True, |
||||
|
executor: Optional["ThreadPoolExecutor"] = None, |
||||
|
) -> Callable[[Callable[..., Any]], SyncToAsync]: |
||||
|
... |
||||
|
|
||||
|
|
||||
|
@overload |
||||
|
def sync_to_async( |
||||
|
func: Callable[..., Any], |
||||
|
thread_sensitive: bool = True, |
||||
|
executor: Optional["ThreadPoolExecutor"] = None, |
||||
|
) -> SyncToAsync: |
||||
|
... |
||||
|
|
||||
|
|
||||
|
def sync_to_async( |
||||
|
func=None, |
||||
|
thread_sensitive=True, |
||||
|
executor=None, |
||||
|
): |
||||
|
if func is None: |
||||
|
return lambda f: SyncToAsync( |
||||
|
f, |
||||
|
thread_sensitive=thread_sensitive, |
||||
|
executor=executor, |
||||
|
) |
||||
|
return SyncToAsync( |
||||
|
func, |
||||
|
thread_sensitive=thread_sensitive, |
||||
|
executor=executor, |
||||
|
) |
@ -0,0 +1,97 @@ |
|||||
|
import asyncio |
||||
|
import time |
||||
|
|
||||
|
from .compatibility import guarantee_single_callable |
||||
|
from .timeout import timeout as async_timeout |
||||
|
|
||||
|
|
||||
|
class ApplicationCommunicator: |
||||
|
""" |
||||
|
Runs an ASGI application in a test mode, allowing sending of |
||||
|
messages to it and retrieval of messages it sends. |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, application, scope): |
||||
|
self.application = guarantee_single_callable(application) |
||||
|
self.scope = scope |
||||
|
self.input_queue = asyncio.Queue() |
||||
|
self.output_queue = asyncio.Queue() |
||||
|
self.future = asyncio.ensure_future( |
||||
|
self.application(scope, self.input_queue.get, self.output_queue.put) |
||||
|
) |
||||
|
|
||||
|
async def wait(self, timeout=1): |
||||
|
""" |
||||
|
Waits for the application to stop itself and returns any exceptions. |
||||
|
""" |
||||
|
try: |
||||
|
async with async_timeout(timeout): |
||||
|
try: |
||||
|
await self.future |
||||
|
self.future.result() |
||||
|
except asyncio.CancelledError: |
||||
|
pass |
||||
|
finally: |
||||
|
if not self.future.done(): |
||||
|
self.future.cancel() |
||||
|
try: |
||||
|
await self.future |
||||
|
except asyncio.CancelledError: |
||||
|
pass |
||||
|
|
||||
|
def stop(self, exceptions=True): |
||||
|
if not self.future.done(): |
||||
|
self.future.cancel() |
||||
|
elif exceptions: |
||||
|
# Give a chance to raise any exceptions |
||||
|
self.future.result() |
||||
|
|
||||
|
def __del__(self): |
||||
|
# Clean up on deletion |
||||
|
try: |
||||
|
self.stop(exceptions=False) |
||||
|
except RuntimeError: |
||||
|
# Event loop already stopped |
||||
|
pass |
||||
|
|
||||
|
async def send_input(self, message): |
||||
|
""" |
||||
|
Sends a single message to the application |
||||
|
""" |
||||
|
# Give it the message |
||||
|
await self.input_queue.put(message) |
||||
|
|
||||
|
async def receive_output(self, timeout=1): |
||||
|
""" |
||||
|
Receives a single message from the application, with optional timeout. |
||||
|
""" |
||||
|
# Make sure there's not an exception to raise from the task |
||||
|
if self.future.done(): |
||||
|
self.future.result() |
||||
|
# Wait and receive the message |
||||
|
try: |
||||
|
async with async_timeout(timeout): |
||||
|
return await self.output_queue.get() |
||||
|
except asyncio.TimeoutError as e: |
||||
|
# See if we have another error to raise inside |
||||
|
if self.future.done(): |
||||
|
self.future.result() |
||||
|
else: |
||||
|
self.future.cancel() |
||||
|
try: |
||||
|
await self.future |
||||
|
except asyncio.CancelledError: |
||||
|
pass |
||||
|
raise e |
||||
|
|
||||
|
async def receive_nothing(self, timeout=0.1, interval=0.01): |
||||
|
""" |
||||
|
Checks that there is no message to receive in the given time. |
||||
|
""" |
||||
|
# `interval` has precedence over `timeout` |
||||
|
start = time.monotonic() |
||||
|
while time.monotonic() - start < timeout: |
||||
|
if not self.output_queue.empty(): |
||||
|
return False |
||||
|
await asyncio.sleep(interval) |
||||
|
return self.output_queue.empty() |
@ -0,0 +1,112 @@ |
|||||
|
# This code is originally sourced from the aio-libs project "async_timeout", |
||||
|
# under the Apache 2.0 license. You may see the original project at |
||||
|
# https://github.com/aio-libs/async-timeout |
||||
|
|
||||
|
# It is vendored here to reduce chain-dependencies on this library, and |
||||
|
# modified slightly to remove some features we don't use. |
||||
|
|
||||
|
|
||||
|
import asyncio |
||||
|
from types import TracebackType |
||||
|
from typing import Any, Optional, Type |
||||
|
|
||||
|
|
||||
|
class timeout: |
||||
|
"""timeout context manager. |
||||
|
|
||||
|
Useful in cases when you want to apply timeout logic around block |
||||
|
of code or in cases when asyncio.wait_for is not suitable. For example: |
||||
|
|
||||
|
>>> with timeout(0.001): |
||||
|
... async with aiohttp.get('https://github.com') as r: |
||||
|
... await r.text() |
||||
|
|
||||
|
|
||||
|
timeout - value in seconds or None to disable timeout logic |
||||
|
loop - asyncio compatible event loop |
||||
|
""" |
||||
|
|
||||
|
def __init__( |
||||
|
self, |
||||
|
timeout: Optional[float], |
||||
|
*, |
||||
|
loop: Optional[asyncio.AbstractEventLoop] = None, |
||||
|
) -> None: |
||||
|
self._timeout = timeout |
||||
|
if loop is None: |
||||
|
loop = asyncio.get_event_loop() |
||||
|
self._loop = loop |
||||
|
self._task = None # type: Optional[asyncio.Task[Any]] |
||||
|
self._cancelled = False |
||||
|
self._cancel_handler = None # type: Optional[asyncio.Handle] |
||||
|
self._cancel_at = None # type: Optional[float] |
||||
|
|
||||
|
def __enter__(self) -> "timeout": |
||||
|
return self._do_enter() |
||||
|
|
||||
|
def __exit__( |
||||
|
self, |
||||
|
exc_type: Type[BaseException], |
||||
|
exc_val: BaseException, |
||||
|
exc_tb: TracebackType, |
||||
|
) -> Optional[bool]: |
||||
|
self._do_exit(exc_type) |
||||
|
return None |
||||
|
|
||||
|
async def __aenter__(self) -> "timeout": |
||||
|
return self._do_enter() |
||||
|
|
||||
|
async def __aexit__( |
||||
|
self, |
||||
|
exc_type: Type[BaseException], |
||||
|
exc_val: BaseException, |
||||
|
exc_tb: TracebackType, |
||||
|
) -> None: |
||||
|
self._do_exit(exc_type) |
||||
|
|
||||
|
@property |
||||
|
def expired(self) -> bool: |
||||
|
return self._cancelled |
||||
|
|
||||
|
@property |
||||
|
def remaining(self) -> Optional[float]: |
||||
|
if self._cancel_at is not None: |
||||
|
return max(self._cancel_at - self._loop.time(), 0.0) |
||||
|
else: |
||||
|
return None |
||||
|
|
||||
|
def _do_enter(self) -> "timeout": |
||||
|
# Support Tornado 5- without timeout |
||||
|
# Details: https://github.com/python/asyncio/issues/392 |
||||
|
if self._timeout is None: |
||||
|
return self |
||||
|
|
||||
|
self._task = asyncio.current_task(self._loop) |
||||
|
if self._task is None: |
||||
|
raise RuntimeError( |
||||
|
"Timeout context manager should be used " "inside a task" |
||||
|
) |
||||
|
|
||||
|
if self._timeout <= 0: |
||||
|
self._loop.call_soon(self._cancel_task) |
||||
|
return self |
||||
|
|
||||
|
self._cancel_at = self._loop.time() + self._timeout |
||||
|
self._cancel_handler = self._loop.call_at(self._cancel_at, self._cancel_task) |
||||
|
return self |
||||
|
|
||||
|
def _do_exit(self, exc_type: Type[BaseException]) -> None: |
||||
|
if exc_type is asyncio.CancelledError and self._cancelled: |
||||
|
self._cancel_handler = None |
||||
|
self._task = None |
||||
|
raise asyncio.TimeoutError |
||||
|
if self._timeout is not None and self._cancel_handler is not None: |
||||
|
self._cancel_handler.cancel() |
||||
|
self._cancel_handler = None |
||||
|
self._task = None |
||||
|
return None |
||||
|
|
||||
|
def _cancel_task(self) -> None: |
||||
|
if self._task is not None: |
||||
|
self._task.cancel() |
||||
|
self._cancelled = True |
@ -0,0 +1,242 @@ |
|||||
|
import sys |
||||
|
from typing import Awaitable, Callable, Dict, Iterable, Optional, Tuple, Type, Union |
||||
|
|
||||
|
if sys.version_info >= (3, 8): |
||||
|
from typing import Literal, Protocol, TypedDict |
||||
|
else: |
||||
|
from typing_extensions import Literal, Protocol, TypedDict |
||||
|
|
||||
|
__all__ = ( |
||||
|
"ASGIVersions", |
||||
|
"HTTPScope", |
||||
|
"WebSocketScope", |
||||
|
"LifespanScope", |
||||
|
"WWWScope", |
||||
|
"Scope", |
||||
|
"HTTPRequestEvent", |
||||
|
"HTTPResponseStartEvent", |
||||
|
"HTTPResponseBodyEvent", |
||||
|
"HTTPServerPushEvent", |
||||
|
"HTTPDisconnectEvent", |
||||
|
"WebSocketConnectEvent", |
||||
|
"WebSocketAcceptEvent", |
||||
|
"WebSocketReceiveEvent", |
||||
|
"WebSocketSendEvent", |
||||
|
"WebSocketResponseStartEvent", |
||||
|
"WebSocketResponseBodyEvent", |
||||
|
"WebSocketDisconnectEvent", |
||||
|
"WebSocketCloseEvent", |
||||
|
"LifespanStartupEvent", |
||||
|
"LifespanShutdownEvent", |
||||
|
"LifespanStartupCompleteEvent", |
||||
|
"LifespanStartupFailedEvent", |
||||
|
"LifespanShutdownCompleteEvent", |
||||
|
"LifespanShutdownFailedEvent", |
||||
|
"ASGIReceiveEvent", |
||||
|
"ASGISendEvent", |
||||
|
"ASGIReceiveCallable", |
||||
|
"ASGISendCallable", |
||||
|
"ASGI2Protocol", |
||||
|
"ASGI2Application", |
||||
|
"ASGI3Application", |
||||
|
"ASGIApplication", |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class ASGIVersions(TypedDict): |
||||
|
spec_version: str |
||||
|
version: Union[Literal["2.0"], Literal["3.0"]] |
||||
|
|
||||
|
|
||||
|
class HTTPScope(TypedDict): |
||||
|
type: Literal["http"] |
||||
|
asgi: ASGIVersions |
||||
|
http_version: str |
||||
|
method: str |
||||
|
scheme: str |
||||
|
path: str |
||||
|
raw_path: bytes |
||||
|
query_string: bytes |
||||
|
root_path: str |
||||
|
headers: Iterable[Tuple[bytes, bytes]] |
||||
|
client: Optional[Tuple[str, int]] |
||||
|
server: Optional[Tuple[str, Optional[int]]] |
||||
|
extensions: Optional[Dict[str, Dict[object, object]]] |
||||
|
|
||||
|
|
||||
|
class WebSocketScope(TypedDict): |
||||
|
type: Literal["websocket"] |
||||
|
asgi: ASGIVersions |
||||
|
http_version: str |
||||
|
scheme: str |
||||
|
path: str |
||||
|
raw_path: bytes |
||||
|
query_string: bytes |
||||
|
root_path: str |
||||
|
headers: Iterable[Tuple[bytes, bytes]] |
||||
|
client: Optional[Tuple[str, int]] |
||||
|
server: Optional[Tuple[str, Optional[int]]] |
||||
|
subprotocols: Iterable[str] |
||||
|
extensions: Optional[Dict[str, Dict[object, object]]] |
||||
|
|
||||
|
|
||||
|
class LifespanScope(TypedDict): |
||||
|
type: Literal["lifespan"] |
||||
|
asgi: ASGIVersions |
||||
|
|
||||
|
|
||||
|
WWWScope = Union[HTTPScope, WebSocketScope] |
||||
|
Scope = Union[HTTPScope, WebSocketScope, LifespanScope] |
||||
|
|
||||
|
|
||||
|
class HTTPRequestEvent(TypedDict): |
||||
|
type: Literal["http.request"] |
||||
|
body: bytes |
||||
|
more_body: bool |
||||
|
|
||||
|
|
||||
|
class HTTPResponseStartEvent(TypedDict): |
||||
|
type: Literal["http.response.start"] |
||||
|
status: int |
||||
|
headers: Iterable[Tuple[bytes, bytes]] |
||||
|
|
||||
|
|
||||
|
class HTTPResponseBodyEvent(TypedDict): |
||||
|
type: Literal["http.response.body"] |
||||
|
body: bytes |
||||
|
more_body: bool |
||||
|
|
||||
|
|
||||
|
class HTTPServerPushEvent(TypedDict): |
||||
|
type: Literal["http.response.push"] |
||||
|
path: str |
||||
|
headers: Iterable[Tuple[bytes, bytes]] |
||||
|
|
||||
|
|
||||
|
class HTTPDisconnectEvent(TypedDict): |
||||
|
type: Literal["http.disconnect"] |
||||
|
|
||||
|
|
||||
|
class WebSocketConnectEvent(TypedDict): |
||||
|
type: Literal["websocket.connect"] |
||||
|
|
||||
|
|
||||
|
class WebSocketAcceptEvent(TypedDict): |
||||
|
type: Literal["websocket.accept"] |
||||
|
subprotocol: Optional[str] |
||||
|
headers: Iterable[Tuple[bytes, bytes]] |
||||
|
|
||||
|
|
||||
|
class WebSocketReceiveEvent(TypedDict): |
||||
|
type: Literal["websocket.receive"] |
||||
|
bytes: Optional[bytes] |
||||
|
text: Optional[str] |
||||
|
|
||||
|
|
||||
|
class WebSocketSendEvent(TypedDict): |
||||
|
type: Literal["websocket.send"] |
||||
|
bytes: Optional[bytes] |
||||
|
text: Optional[str] |
||||
|
|
||||
|
|
||||
|
class WebSocketResponseStartEvent(TypedDict): |
||||
|
type: Literal["websocket.http.response.start"] |
||||
|
status: int |
||||
|
headers: Iterable[Tuple[bytes, bytes]] |
||||
|
|
||||
|
|
||||
|
class WebSocketResponseBodyEvent(TypedDict): |
||||
|
type: Literal["websocket.http.response.body"] |
||||
|
body: bytes |
||||
|
more_body: bool |
||||
|
|
||||
|
|
||||
|
class WebSocketDisconnectEvent(TypedDict): |
||||
|
type: Literal["websocket.disconnect"] |
||||
|
code: int |
||||
|
|
||||
|
|
||||
|
class WebSocketCloseEvent(TypedDict): |
||||
|
type: Literal["websocket.close"] |
||||
|
code: int |
||||
|
reason: Optional[str] |
||||
|
|
||||
|
|
||||
|
class LifespanStartupEvent(TypedDict): |
||||
|
type: Literal["lifespan.startup"] |
||||
|
|
||||
|
|
||||
|
class LifespanShutdownEvent(TypedDict): |
||||
|
type: Literal["lifespan.shutdown"] |
||||
|
|
||||
|
|
||||
|
class LifespanStartupCompleteEvent(TypedDict): |
||||
|
type: Literal["lifespan.startup.complete"] |
||||
|
|
||||
|
|
||||
|
class LifespanStartupFailedEvent(TypedDict): |
||||
|
type: Literal["lifespan.startup.failed"] |
||||
|
message: str |
||||
|
|
||||
|
|
||||
|
class LifespanShutdownCompleteEvent(TypedDict): |
||||
|
type: Literal["lifespan.shutdown.complete"] |
||||
|
|
||||
|
|
||||
|
class LifespanShutdownFailedEvent(TypedDict): |
||||
|
type: Literal["lifespan.shutdown.failed"] |
||||
|
message: str |
||||
|
|
||||
|
|
||||
|
ASGIReceiveEvent = Union[ |
||||
|
HTTPRequestEvent, |
||||
|
HTTPDisconnectEvent, |
||||
|
WebSocketConnectEvent, |
||||
|
WebSocketReceiveEvent, |
||||
|
WebSocketDisconnectEvent, |
||||
|
LifespanStartupEvent, |
||||
|
LifespanShutdownEvent, |
||||
|
] |
||||
|
|
||||
|
|
||||
|
ASGISendEvent = Union[ |
||||
|
HTTPResponseStartEvent, |
||||
|
HTTPResponseBodyEvent, |
||||
|
HTTPServerPushEvent, |
||||
|
HTTPDisconnectEvent, |
||||
|
WebSocketAcceptEvent, |
||||
|
WebSocketSendEvent, |
||||
|
WebSocketResponseStartEvent, |
||||
|
WebSocketResponseBodyEvent, |
||||
|
WebSocketCloseEvent, |
||||
|
LifespanStartupCompleteEvent, |
||||
|
LifespanStartupFailedEvent, |
||||
|
LifespanShutdownCompleteEvent, |
||||
|
LifespanShutdownFailedEvent, |
||||
|
] |
||||
|
|
||||
|
|
||||
|
ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]] |
||||
|
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]] |
||||
|
|
||||
|
|
||||
|
class ASGI2Protocol(Protocol): |
||||
|
def __init__(self, scope: Scope) -> None: |
||||
|
... |
||||
|
|
||||
|
async def __call__( |
||||
|
self, receive: ASGIReceiveCallable, send: ASGISendCallable |
||||
|
) -> None: |
||||
|
... |
||||
|
|
||||
|
|
||||
|
ASGI2Application = Type[ASGI2Protocol] |
||||
|
ASGI3Application = Callable[ |
||||
|
[ |
||||
|
Scope, |
||||
|
ASGIReceiveCallable, |
||||
|
ASGISendCallable, |
||||
|
], |
||||
|
Awaitable[None], |
||||
|
] |
||||
|
ASGIApplication = Union[ASGI2Application, ASGI3Application] |
@ -0,0 +1,162 @@ |
|||||
|
from io import BytesIO |
||||
|
from tempfile import SpooledTemporaryFile |
||||
|
|
||||
|
from asgiref.sync import AsyncToSync, sync_to_async |
||||
|
|
||||
|
|
||||
|
class WsgiToAsgi: |
||||
|
""" |
||||
|
Wraps a WSGI application to make it into an ASGI application. |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, wsgi_application): |
||||
|
self.wsgi_application = wsgi_application |
||||
|
|
||||
|
async def __call__(self, scope, receive, send): |
||||
|
""" |
||||
|
ASGI application instantiation point. |
||||
|
We return a new WsgiToAsgiInstance here with the WSGI app |
||||
|
and the scope, ready to respond when it is __call__ed. |
||||
|
""" |
||||
|
await WsgiToAsgiInstance(self.wsgi_application)(scope, receive, send) |
||||
|
|
||||
|
|
||||
|
class WsgiToAsgiInstance: |
||||
|
""" |
||||
|
Per-socket instance of a wrapped WSGI application |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, wsgi_application): |
||||
|
self.wsgi_application = wsgi_application |
||||
|
self.response_started = False |
||||
|
self.response_content_length = None |
||||
|
|
||||
|
async def __call__(self, scope, receive, send): |
||||
|
if scope["type"] != "http": |
||||
|
raise ValueError("WSGI wrapper received a non-HTTP scope") |
||||
|
self.scope = scope |
||||
|
with SpooledTemporaryFile(max_size=65536) as body: |
||||
|
# Alright, wait for the http.request messages |
||||
|
while True: |
||||
|
message = await receive() |
||||
|
if message["type"] != "http.request": |
||||
|
raise ValueError("WSGI wrapper received a non-HTTP-request message") |
||||
|
body.write(message.get("body", b"")) |
||||
|
if not message.get("more_body"): |
||||
|
break |
||||
|
body.seek(0) |
||||
|
# Wrap send so it can be called from the subthread |
||||
|
self.sync_send = AsyncToSync(send) |
||||
|
# Call the WSGI app |
||||
|
await self.run_wsgi_app(body) |
||||
|
|
||||
|
def build_environ(self, scope, body): |
||||
|
""" |
||||
|
Builds a scope and request body into a WSGI environ object. |
||||
|
""" |
||||
|
environ = { |
||||
|
"REQUEST_METHOD": scope["method"], |
||||
|
"SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"), |
||||
|
"PATH_INFO": scope["path"].encode("utf8").decode("latin1"), |
||||
|
"QUERY_STRING": scope["query_string"].decode("ascii"), |
||||
|
"SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], |
||||
|
"wsgi.version": (1, 0), |
||||
|
"wsgi.url_scheme": scope.get("scheme", "http"), |
||||
|
"wsgi.input": body, |
||||
|
"wsgi.errors": BytesIO(), |
||||
|
"wsgi.multithread": True, |
||||
|
"wsgi.multiprocess": True, |
||||
|
"wsgi.run_once": False, |
||||
|
} |
||||
|
# Get server name and port - required in WSGI, not in ASGI |
||||
|
if "server" in scope: |
||||
|
environ["SERVER_NAME"] = scope["server"][0] |
||||
|
environ["SERVER_PORT"] = str(scope["server"][1]) |
||||
|
else: |
||||
|
environ["SERVER_NAME"] = "localhost" |
||||
|
environ["SERVER_PORT"] = "80" |
||||
|
|
||||
|
if "client" in scope: |
||||
|
environ["REMOTE_ADDR"] = scope["client"][0] |
||||
|
|
||||
|
# Go through headers and make them into environ entries |
||||
|
for name, value in self.scope.get("headers", []): |
||||
|
name = name.decode("latin1") |
||||
|
if name == "content-length": |
||||
|
corrected_name = "CONTENT_LENGTH" |
||||
|
elif name == "content-type": |
||||
|
corrected_name = "CONTENT_TYPE" |
||||
|
else: |
||||
|
corrected_name = "HTTP_%s" % name.upper().replace("-", "_") |
||||
|
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case |
||||
|
value = value.decode("latin1") |
||||
|
if corrected_name in environ: |
||||
|
value = environ[corrected_name] + "," + value |
||||
|
environ[corrected_name] = value |
||||
|
return environ |
||||
|
|
||||
|
def start_response(self, status, response_headers, exc_info=None): |
||||
|
""" |
||||
|
WSGI start_response callable. |
||||
|
""" |
||||
|
# Don't allow re-calling once response has begun |
||||
|
if self.response_started: |
||||
|
raise exc_info[1].with_traceback(exc_info[2]) |
||||
|
# Don't allow re-calling without exc_info |
||||
|
if hasattr(self, "response_start") and exc_info is None: |
||||
|
raise ValueError( |
||||
|
"You cannot call start_response a second time without exc_info" |
||||
|
) |
||||
|
# Extract status code |
||||
|
status_code, _ = status.split(" ", 1) |
||||
|
status_code = int(status_code) |
||||
|
# Extract headers |
||||
|
headers = [ |
||||
|
(name.lower().encode("ascii"), value.encode("ascii")) |
||||
|
for name, value in response_headers |
||||
|
] |
||||
|
# Extract content-length |
||||
|
self.response_content_length = None |
||||
|
for name, value in response_headers: |
||||
|
if name.lower() == "content-length": |
||||
|
self.response_content_length = int(value) |
||||
|
# Build and send response start message. |
||||
|
self.response_start = { |
||||
|
"type": "http.response.start", |
||||
|
"status": status_code, |
||||
|
"headers": headers, |
||||
|
} |
||||
|
|
||||
|
@sync_to_async |
||||
|
def run_wsgi_app(self, body): |
||||
|
""" |
||||
|
Called in a subthread to run the WSGI app. We encapsulate like |
||||
|
this so that the start_response callable is called in the same thread. |
||||
|
""" |
||||
|
# Translate the scope and incoming request body into a WSGI environ |
||||
|
environ = self.build_environ(self.scope, body) |
||||
|
# Run the WSGI app |
||||
|
bytes_sent = 0 |
||||
|
for output in self.wsgi_application(environ, self.start_response): |
||||
|
# If this is the first response, include the response headers |
||||
|
if not self.response_started: |
||||
|
self.response_started = True |
||||
|
self.sync_send(self.response_start) |
||||
|
# If the application supplies a Content-Length header |
||||
|
if self.response_content_length is not None: |
||||
|
# The server should not transmit more bytes to the client than the header allows |
||||
|
bytes_allowed = self.response_content_length - bytes_sent |
||||
|
if len(output) > bytes_allowed: |
||||
|
output = output[:bytes_allowed] |
||||
|
self.sync_send( |
||||
|
{"type": "http.response.body", "body": output, "more_body": True} |
||||
|
) |
||||
|
bytes_sent += len(output) |
||||
|
# The server should stop iterating over the response when enough data has been sent |
||||
|
if bytes_sent == self.response_content_length: |
||||
|
break |
||||
|
# Close connection |
||||
|
if not self.response_started: |
||||
|
self.response_started = True |
||||
|
self.sync_send(self.response_start) |
||||
|
self.sync_send({"type": "http.response.body"}) |
@ -0,0 +1 @@ |
|||||
|
__version__ = "1.14.0" |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,22 @@ |
|||||
|
class KeepContext: |
||||
|
""" |
||||
|
Context manager that receives a `django.template.Context` instance and a list of keys |
||||
|
|
||||
|
Once the context manager is exited, it removes `keys` from the context, to avoid |
||||
|
side effects in later layout objects that may use the same context variables. |
||||
|
|
||||
|
Layout objects should use `extra_context` to introduce context variables, never |
||||
|
touch context object themselves, that could introduce side effects. |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, context, keys): |
||||
|
self.context = context |
||||
|
self.keys = keys |
||||
|
|
||||
|
def __enter__(self): |
||||
|
pass |
||||
|
|
||||
|
def __exit__(self, type, value, traceback): |
||||
|
for key in list(self.keys): |
||||
|
if key in self.context: |
||||
|
del self.context[key] |
@ -0,0 +1,504 @@ |
|||||
|
from random import randint |
||||
|
|
||||
|
from django.template import Template |
||||
|
from django.template.loader import render_to_string |
||||
|
from django.utils.text import slugify |
||||
|
|
||||
|
from .layout import Div, Field, LayoutObject, TemplateNameMixin |
||||
|
from .utils import TEMPLATE_PACK, flatatt, render_field |
||||
|
|
||||
|
|
||||
|
class PrependedAppendedText(Field): |
||||
|
template = "%s/layout/prepended_appended_text.html" |
||||
|
|
||||
|
def __init__(self, field, prepended_text=None, appended_text=None, input_size=None, *args, **kwargs): |
||||
|
self.field = field |
||||
|
self.appended_text = appended_text |
||||
|
self.prepended_text = prepended_text |
||||
|
if "active" in kwargs: |
||||
|
self.active = kwargs.pop("active") |
||||
|
|
||||
|
self.input_size = input_size |
||||
|
css_class = kwargs.get("css_class", "") |
||||
|
|
||||
|
# Bootstrap 3 |
||||
|
if "input-lg" in css_class: |
||||
|
self.input_size = "input-lg" |
||||
|
if "input-sm" in css_class: |
||||
|
self.input_size = "input-sm" |
||||
|
|
||||
|
super().__init__(field, *args, **kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs): |
||||
|
extra_context = extra_context.copy() if extra_context is not None else {} |
||||
|
extra_context.update( |
||||
|
{ |
||||
|
"crispy_appended_text": self.appended_text, |
||||
|
"crispy_prepended_text": self.prepended_text, |
||||
|
"input_size": self.input_size, |
||||
|
"active": getattr(self, "active", False), |
||||
|
"wrapper_class": self.wrapper_class, |
||||
|
} |
||||
|
) |
||||
|
template = self.get_template_name(template_pack) |
||||
|
return render_field( |
||||
|
self.field, |
||||
|
form, |
||||
|
form_style, |
||||
|
context, |
||||
|
template=template, |
||||
|
attrs=self.attrs, |
||||
|
template_pack=template_pack, |
||||
|
extra_context=extra_context, |
||||
|
**kwargs, |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class AppendedText(PrependedAppendedText): |
||||
|
def __init__(self, field, text, *args, **kwargs): |
||||
|
kwargs.pop("appended_text", None) |
||||
|
kwargs.pop("prepended_text", None) |
||||
|
self.text = text |
||||
|
super().__init__(field, appended_text=text, **kwargs) |
||||
|
|
||||
|
|
||||
|
class PrependedText(PrependedAppendedText): |
||||
|
def __init__(self, field, text, *args, **kwargs): |
||||
|
kwargs.pop("appended_text", None) |
||||
|
kwargs.pop("prepended_text", None) |
||||
|
self.text = text |
||||
|
super().__init__(field, prepended_text=text, **kwargs) |
||||
|
|
||||
|
|
||||
|
class FormActions(LayoutObject): |
||||
|
""" |
||||
|
Bootstrap layout object. It wraps fields in a <div class="form-actions"> |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
FormActions( |
||||
|
HTML(<span style="display: hidden;">Information Saved</span>), |
||||
|
Submit('Save', 'Save', css_class='btn-primary') |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/formactions.html" |
||||
|
|
||||
|
def __init__(self, *fields, **kwargs): |
||||
|
self.fields = list(fields) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.attrs = kwargs |
||||
|
if "css_class" in self.attrs: |
||||
|
self.attrs["class"] = self.attrs.pop("css_class") |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
html = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) |
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"formactions": self, "fields_output": html}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
def flat_attrs(self): |
||||
|
return flatatt(self.attrs) |
||||
|
|
||||
|
|
||||
|
class InlineCheckboxes(Field): |
||||
|
""" |
||||
|
Layout object for rendering checkboxes inline:: |
||||
|
|
||||
|
InlineCheckboxes('field_name') |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/checkboxselectmultiple_inline.html" |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
return super().render( |
||||
|
form, form_style, context, template_pack=template_pack, extra_context={"inline_class": "inline"} |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class InlineRadios(Field): |
||||
|
""" |
||||
|
Layout object for rendering radiobuttons inline:: |
||||
|
|
||||
|
InlineRadios('field_name') |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/radioselect_inline.html" |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
return super().render( |
||||
|
form, form_style, context, template_pack=template_pack, extra_context={"inline_class": "inline"} |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class FieldWithButtons(Div): |
||||
|
""" |
||||
|
A layout object for rendering a single field with any number of buttons. |
||||
|
|
||||
|
Args: |
||||
|
fields : str or LayoutObject |
||||
|
The first positional argument is the field. This can be either the |
||||
|
name of the field as a string or an instance of `Field`. Following |
||||
|
arguments will be rendered as buttons. |
||||
|
input_size : str |
||||
|
Additional CSS class to change the size of the input. e.g. |
||||
|
"input-group-sm". |
||||
|
kwargs |
||||
|
Additional kwargs to be passed to the parent `Div` Layout Object. |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
FieldWithButtons( |
||||
|
Field("password1", css_class="span4"), |
||||
|
StrictButton("Go!", css_id="go-button"), |
||||
|
input_size="input-group-sm", |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/field_with_buttons.html" |
||||
|
field_template = "%s/field.html" |
||||
|
|
||||
|
def __init__(self, *fields, input_size=None, **kwargs): |
||||
|
self.input_size = input_size |
||||
|
super().__init__(*fields, **kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs): |
||||
|
# We first render the buttons |
||||
|
field_template = self.field_template % template_pack |
||||
|
buttons = "".join( |
||||
|
render_field( |
||||
|
field, |
||||
|
form, |
||||
|
form_style, |
||||
|
context, |
||||
|
field_template, |
||||
|
layout_object=self, |
||||
|
template_pack=template_pack, |
||||
|
**kwargs, |
||||
|
) |
||||
|
for field in self.fields[1:] |
||||
|
) |
||||
|
|
||||
|
extra_context = {"div": self, "buttons": buttons} |
||||
|
template = self.get_template_name(template_pack) |
||||
|
|
||||
|
if isinstance(self.fields[0], Field): |
||||
|
# FieldWithButtons(Field('field_name'), StrictButton("go")) |
||||
|
# We render the field passing its name and attributes |
||||
|
return render_field( |
||||
|
self.fields[0][0], |
||||
|
form, |
||||
|
form_style, |
||||
|
context, |
||||
|
template, |
||||
|
attrs=self.fields[0].attrs, |
||||
|
template_pack=template_pack, |
||||
|
extra_context=extra_context, |
||||
|
**kwargs, |
||||
|
) |
||||
|
else: |
||||
|
return render_field( |
||||
|
self.fields[0], form, form_style, context, template, extra_context=extra_context, **kwargs |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class StrictButton(TemplateNameMixin): |
||||
|
""" |
||||
|
Layout object for rendering an HTML button:: |
||||
|
|
||||
|
Button("button content", css_class="extra") |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/button.html" |
||||
|
field_classes = "btn" |
||||
|
|
||||
|
def __init__(self, content, **kwargs): |
||||
|
self.content = content |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
|
||||
|
kwargs.setdefault("type", "button") |
||||
|
|
||||
|
# We turn css_id and css_class into id and class |
||||
|
if "css_id" in kwargs: |
||||
|
kwargs["id"] = kwargs.pop("css_id") |
||||
|
kwargs["class"] = self.field_classes |
||||
|
if "css_class" in kwargs: |
||||
|
kwargs["class"] += " %s" % kwargs.pop("css_class") |
||||
|
|
||||
|
self.flat_attrs = flatatt(kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
self.content = Template(str(self.content)).render(context) |
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"button": self}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class Container(Div): |
||||
|
""" |
||||
|
Base class used for `Tab` and `AccordionGroup`, represents a basic container concept |
||||
|
""" |
||||
|
|
||||
|
css_class = "" |
||||
|
|
||||
|
def __init__(self, name, *fields, **kwargs): |
||||
|
super().__init__(*fields, **kwargs) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.name = name |
||||
|
self._active_originally_included = "active" in kwargs |
||||
|
self.active = kwargs.pop("active", False) |
||||
|
if not self.css_id: |
||||
|
self.css_id = slugify(self.name, allow_unicode=True) |
||||
|
|
||||
|
def __contains__(self, field_name): |
||||
|
""" |
||||
|
check if field_name is contained within tab. |
||||
|
""" |
||||
|
return field_name in map(lambda pointer: pointer[1], self.get_field_names()) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
if self.active: |
||||
|
if "active" not in self.css_class: |
||||
|
self.css_class += " active" |
||||
|
else: |
||||
|
self.css_class = self.css_class.replace("active", "") |
||||
|
return super().render(form, form_style, context, template_pack) |
||||
|
|
||||
|
|
||||
|
class ContainerHolder(Div): |
||||
|
""" |
||||
|
Base class used for `TabHolder` and `Accordion`, groups containers |
||||
|
""" |
||||
|
|
||||
|
def first_container_with_errors(self, errors): |
||||
|
""" |
||||
|
Returns the first container with errors, otherwise returns None. |
||||
|
""" |
||||
|
for tab in self.fields: |
||||
|
errors_here = any(error in tab for error in errors) |
||||
|
if errors_here: |
||||
|
return tab |
||||
|
return None |
||||
|
|
||||
|
def open_target_group_for_form(self, form): |
||||
|
""" |
||||
|
Makes sure that the first group that should be open is open. |
||||
|
This is either the first group with errors or the first group |
||||
|
in the container, unless that first group was originally set to |
||||
|
active=False. |
||||
|
""" |
||||
|
target = self.first_container_with_errors(form.errors.keys()) |
||||
|
if target is None: |
||||
|
target = self.fields[0] |
||||
|
if not getattr(target, "_active_originally_included", None): |
||||
|
target.active = True |
||||
|
return target |
||||
|
|
||||
|
target.active = True |
||||
|
return target |
||||
|
|
||||
|
|
||||
|
class Tab(Container): |
||||
|
""" |
||||
|
Tab object. It wraps fields in a div whose default class is "tab-pane" and |
||||
|
takes a name as first argument. Example:: |
||||
|
|
||||
|
Tab('tab_name', 'form_field_1', 'form_field_2', 'form_field_3') |
||||
|
""" |
||||
|
|
||||
|
css_class = "tab-pane" |
||||
|
link_template = "%s/layout/tab-link.html" |
||||
|
|
||||
|
def render_link(self, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
""" |
||||
|
Render the link for the tab-pane. It must be called after render so css_class is updated |
||||
|
with active if needed. |
||||
|
""" |
||||
|
link_template = self.link_template % template_pack |
||||
|
return render_to_string(link_template, {"link": self}) |
||||
|
|
||||
|
|
||||
|
class TabHolder(ContainerHolder): |
||||
|
""" |
||||
|
TabHolder object. It wraps Tab objects in a container. Requires bootstrap-tab.js:: |
||||
|
|
||||
|
TabHolder( |
||||
|
Tab('form_field_1', 'form_field_2'), |
||||
|
Tab('form_field_3') |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/tab.html" |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
for tab in self.fields: |
||||
|
tab.active = False |
||||
|
|
||||
|
# Open the group that should be open. |
||||
|
self.open_target_group_for_form(form) |
||||
|
content = self.get_rendered_fields(form, form_style, context, template_pack) |
||||
|
links = "".join(tab.render_link(template_pack) for tab in self.fields) |
||||
|
|
||||
|
context.update({"tabs": self, "links": links, "content": content}) |
||||
|
template = self.get_template_name(template_pack) |
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class AccordionGroup(Container): |
||||
|
""" |
||||
|
Accordion Group (pane) object. It wraps given fields inside an accordion |
||||
|
tab. It takes accordion tab name as first argument:: |
||||
|
|
||||
|
AccordionGroup("group name", "form_field_1", "form_field_2") |
||||
|
""" |
||||
|
|
||||
|
template = "%s/accordion-group.html" |
||||
|
data_parent = "" # accordion parent div id. |
||||
|
|
||||
|
|
||||
|
class Accordion(ContainerHolder): |
||||
|
""" |
||||
|
Accordion menu object. It wraps `AccordionGroup` objects in a container:: |
||||
|
|
||||
|
Accordion( |
||||
|
AccordionGroup("group name", "form_field_1", "form_field_2"), |
||||
|
AccordionGroup("another group name", "form_field") |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/accordion.html" |
||||
|
|
||||
|
def __init__(self, *args, **kwargs): |
||||
|
super().__init__(*args, **kwargs) |
||||
|
|
||||
|
# Accordion needs to have a unique id |
||||
|
if not self.css_id: |
||||
|
self.css_id = "-".join(["accordion", str(randint(1000, 9999))]) |
||||
|
|
||||
|
# AccordionGroup need to have 'data-parent="#Accordion.id"' |
||||
|
for accordion_group in args: |
||||
|
accordion_group.data_parent = self.css_id |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
content = "" |
||||
|
|
||||
|
# Open the group that should be open. |
||||
|
self.open_target_group_for_form(form) |
||||
|
|
||||
|
for group in self.fields: |
||||
|
group.data_parent = self.css_id |
||||
|
content += render_field(group, form, form_style, context, template_pack=template_pack, **kwargs) |
||||
|
|
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"accordion": self, "content": content}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class Alert(Div): |
||||
|
""" |
||||
|
`Alert` generates markup in the form of an alert dialog |
||||
|
|
||||
|
Alert(content='<strong>Warning!</strong> Best check yo self, you're not looking too good.') |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/alert.html" |
||||
|
css_class = "alert" |
||||
|
|
||||
|
def __init__(self, content, dismiss=True, block=False, **kwargs): |
||||
|
fields = [] |
||||
|
if block: |
||||
|
self.css_class += " alert-block" |
||||
|
Div.__init__(self, *fields, **kwargs) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.content = content |
||||
|
self.dismiss = dismiss |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"alert": self, "content": self.content, "dismiss": self.dismiss}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class UneditableField(Field): |
||||
|
""" |
||||
|
Layout object for rendering fields as uneditable in bootstrap |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
UneditableField('field_name', css_class="input-xlarge") |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/uneditable_input.html" |
||||
|
|
||||
|
def __init__(self, field, *args, **kwargs): |
||||
|
self.attrs = {"class": "uneditable-input"} |
||||
|
super().__init__(field, *args, **kwargs) |
||||
|
|
||||
|
|
||||
|
class InlineField(Field): |
||||
|
template = "%s/layout/inline_field.html" |
||||
|
|
||||
|
|
||||
|
class Modal(LayoutObject): |
||||
|
""" |
||||
|
Boostrap layout object for rendering crispy forms objects inside a bootstrap modal. |
||||
|
|
||||
|
The following attributes can be set: |
||||
|
- `css_id`: modal's DOM id |
||||
|
- `css_class`: modal's DOM classes |
||||
|
- NOTE: "modal" and "fade" are applied by default on the template |
||||
|
- `title`: text to display in the modal's header |
||||
|
- NOTE: text will be wrapped in a <h5> tag |
||||
|
- `title_id`: title's DOM id |
||||
|
- `title_class`: titles's DOM classes |
||||
|
- NOTE: "modal-title" is applied by default on the template |
||||
|
- template |
||||
|
The default template which this Layout Object will be rendered |
||||
|
with |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
Modal( |
||||
|
'field1', |
||||
|
Div('field2'), |
||||
|
css_id="modal-id-ex", |
||||
|
css_class="modal-class-ex, |
||||
|
title="This is my modal", |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/modal.html" |
||||
|
|
||||
|
def __init__( |
||||
|
self, |
||||
|
*fields, |
||||
|
template=None, |
||||
|
css_id="modal_id", |
||||
|
title="Modal Title", |
||||
|
title_id="modal_title_id", |
||||
|
css_class="", |
||||
|
title_class="", |
||||
|
**kwargs, |
||||
|
): |
||||
|
|
||||
|
self.fields = list(fields) |
||||
|
self.template = template or self.template |
||||
|
self.css_id = css_id |
||||
|
self.css_class = css_class |
||||
|
self.title = title |
||||
|
self.title_id = title_id |
||||
|
self.title_class = title_class |
||||
|
|
||||
|
kwargs = {**kwargs, "tabindex": "-1", "role": "dialog", "aria-labelledby": "%s-label" % self.title_id} |
||||
|
|
||||
|
self.flat_attrs = flatatt(kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) |
||||
|
template = self.get_template_name(template_pack) |
||||
|
|
||||
|
return render_to_string(template, {"modal": self, "fields": fields}) |
@ -0,0 +1,16 @@ |
|||||
|
class CrispyError(Exception): |
||||
|
pass |
||||
|
|
||||
|
|
||||
|
class FormHelpersException(CrispyError): |
||||
|
""" |
||||
|
This is raised when building a form via helpers throws an error. |
||||
|
We want to catch form helper errors as soon as possible because |
||||
|
debugging templatetags is never fun. |
||||
|
""" |
||||
|
|
||||
|
pass |
||||
|
|
||||
|
|
||||
|
class DynamicError(CrispyError): |
||||
|
pass |
@ -0,0 +1,388 @@ |
|||||
|
import re |
||||
|
|
||||
|
from django.urls import NoReverseMatch, reverse |
||||
|
from django.utils.safestring import mark_safe |
||||
|
|
||||
|
from crispy_forms.exceptions import FormHelpersException |
||||
|
from crispy_forms.layout import Layout |
||||
|
from crispy_forms.layout_slice import LayoutSlice |
||||
|
from crispy_forms.utils import TEMPLATE_PACK, flatatt, list_difference, render_field |
||||
|
|
||||
|
|
||||
|
class DynamicLayoutHandler: |
||||
|
def _check_layout(self): |
||||
|
if self.layout is None: |
||||
|
raise FormHelpersException("You need to set a layout in your FormHelper") |
||||
|
|
||||
|
def _check_layout_and_form(self): |
||||
|
self._check_layout() |
||||
|
if self.form is None: |
||||
|
raise FormHelpersException("You need to pass a form instance to your FormHelper") |
||||
|
|
||||
|
def all(self): |
||||
|
""" |
||||
|
Returns all layout objects of first level of depth |
||||
|
""" |
||||
|
self._check_layout() |
||||
|
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1)) |
||||
|
|
||||
|
def filter(self, *LayoutClasses, **kwargs): |
||||
|
""" |
||||
|
Returns a LayoutSlice pointing to layout objects of type `LayoutClass` |
||||
|
""" |
||||
|
self._check_layout() |
||||
|
max_level = kwargs.pop("max_level", 0) |
||||
|
greedy = kwargs.pop("greedy", False) |
||||
|
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy) |
||||
|
|
||||
|
return LayoutSlice(self.layout, filtered_layout_objects) |
||||
|
|
||||
|
def filter_by_widget(self, widget_type): |
||||
|
""" |
||||
|
Returns a LayoutSlice pointing to fields with widgets of `widget_type` |
||||
|
""" |
||||
|
self._check_layout_and_form() |
||||
|
layout_field_names = self.layout.get_field_names() |
||||
|
|
||||
|
# Let's filter all fields with widgets like widget_type |
||||
|
filtered_fields = [] |
||||
|
for pointer in layout_field_names: |
||||
|
if isinstance(self.form.fields[pointer[1]].widget, widget_type): |
||||
|
filtered_fields.append(pointer) |
||||
|
|
||||
|
return LayoutSlice(self.layout, filtered_fields) |
||||
|
|
||||
|
def exclude_by_widget(self, widget_type): |
||||
|
""" |
||||
|
Returns a LayoutSlice pointing to fields with widgets NOT matching `widget_type` |
||||
|
""" |
||||
|
self._check_layout_and_form() |
||||
|
layout_field_names = self.layout.get_field_names() |
||||
|
|
||||
|
# Let's exclude all fields with widgets like widget_type |
||||
|
filtered_fields = [] |
||||
|
for pointer in layout_field_names: |
||||
|
if not isinstance(self.form.fields[pointer[1]].widget, widget_type): |
||||
|
filtered_fields.append(pointer) |
||||
|
|
||||
|
return LayoutSlice(self.layout, filtered_fields) |
||||
|
|
||||
|
def __getitem__(self, key): |
||||
|
""" |
||||
|
Return a LayoutSlice that makes changes affect the current instance of the layout |
||||
|
and not a copy. |
||||
|
""" |
||||
|
# when key is a string containing the field name |
||||
|
if isinstance(key, str): |
||||
|
# Django templates access FormHelper attributes using dictionary [] operator |
||||
|
# This could be a helper['form_id'] access, not looking for a field |
||||
|
if hasattr(self, key): |
||||
|
return getattr(self, key) |
||||
|
|
||||
|
self._check_layout() |
||||
|
layout_field_names = self.layout.get_field_names() |
||||
|
|
||||
|
filtered_field = [] |
||||
|
for pointer in layout_field_names: |
||||
|
# There can be an empty pointer |
||||
|
if len(pointer) == 2 and pointer[1] == key: |
||||
|
filtered_field.append(pointer) |
||||
|
|
||||
|
return LayoutSlice(self.layout, filtered_field) |
||||
|
|
||||
|
return LayoutSlice(self.layout, key) |
||||
|
|
||||
|
def __setitem__(self, key, value): |
||||
|
self.layout[key] = value |
||||
|
|
||||
|
def __delitem__(self, key): |
||||
|
del self.layout.fields[key] |
||||
|
|
||||
|
def __len__(self): |
||||
|
if self.layout is not None: |
||||
|
return len(self.layout.fields) |
||||
|
else: |
||||
|
return 0 |
||||
|
|
||||
|
|
||||
|
class FormHelper(DynamicLayoutHandler): |
||||
|
""" |
||||
|
This class controls the form rendering behavior of the form passed to |
||||
|
the `{% crispy %}` tag. For doing so you will need to set its attributes |
||||
|
and pass the corresponding helper object to the tag:: |
||||
|
|
||||
|
{% crispy form form.helper %} |
||||
|
|
||||
|
Let's see what attributes you can set and what form behaviors they apply to: |
||||
|
|
||||
|
**form_method**: Specifies form method attribute. |
||||
|
You can set it to 'POST' or 'GET'. Defaults to 'POST' |
||||
|
|
||||
|
**form_action**: Applied to the form action attribute: |
||||
|
- Can be a named url in your URLconf that can be executed via the `{% url %}` template tag. \ |
||||
|
Example: 'show_my_profile'. In your URLconf you could have something like:: |
||||
|
|
||||
|
path('show/profile/', 'show_my_profile_view', name = 'show_my_profile') |
||||
|
|
||||
|
- It can simply point to a URL '/whatever/blabla/'. |
||||
|
|
||||
|
**form_id**: Generates a form id for dom identification. |
||||
|
If no id provided then no id attribute is created on the form. |
||||
|
|
||||
|
**form_class**: String containing separated CSS classes to be applied |
||||
|
to form class attribute. The form will always have by default |
||||
|
'uniForm' class. |
||||
|
|
||||
|
**form_group_wrapper_class**: String containing separated CSS classes to be applied |
||||
|
to each row of inputs. |
||||
|
|
||||
|
**form_tag**: It specifies if <form></form> tags should be rendered when using a Layout. |
||||
|
If set to False it renders the form without the <form></form> tags. Defaults to True. |
||||
|
|
||||
|
**form_error_title**: If a form has `non_field_errors` to display, they |
||||
|
are rendered in a div. You can set title's div with this attribute. |
||||
|
Example: "Oooops!" or "Form Errors" |
||||
|
|
||||
|
**formset_error_title**: If a formset has `non_form_errors` to display, they |
||||
|
are rendered in a div. You can set title's div with this attribute. |
||||
|
|
||||
|
**form_style**: Uni-form has two built in different form styles. You can choose |
||||
|
your favorite. This can be set to "default" or "inline". Defaults to "default". |
||||
|
|
||||
|
**include_media**: Whether to automatically include form media. Set to False if |
||||
|
you want to manually include form media outside the form. Defaults to True. |
||||
|
|
||||
|
Public Methods: |
||||
|
|
||||
|
**add_input(input)**: You can add input buttons using this method. Inputs |
||||
|
added using this method will be rendered at the end of the form/formset. |
||||
|
|
||||
|
**add_layout(layout)**: You can add a `Layout` object to `FormHelper`. The Layout |
||||
|
specifies in a simple, clean and DRY way how the form fields should be rendered. |
||||
|
You can wrap fields, order them, customize pretty much anything in the form. |
||||
|
|
||||
|
Best way to add a helper to a form is adding a property named helper to the form |
||||
|
that returns customized `FormHelper` object:: |
||||
|
|
||||
|
from crispy_forms.helper import FormHelper |
||||
|
from crispy_forms.layout import Submit |
||||
|
|
||||
|
class MyForm(forms.Form): |
||||
|
title = forms.CharField(_("Title")) |
||||
|
|
||||
|
@property |
||||
|
def helper(self): |
||||
|
helper = FormHelper() |
||||
|
helper.form_id = 'this-form-rocks' |
||||
|
helper.form_class = 'search' |
||||
|
helper.add_input(Submit('save', 'save')) |
||||
|
[...] |
||||
|
return helper |
||||
|
|
||||
|
You can use it in a template doing:: |
||||
|
|
||||
|
{% load crispy_forms_tags %} |
||||
|
{% crispy form %} |
||||
|
""" |
||||
|
|
||||
|
_form_method = "post" |
||||
|
_form_action = "" |
||||
|
_form_style = "default" |
||||
|
form = None |
||||
|
form_id = "" |
||||
|
form_class = "" |
||||
|
form_group_wrapper_class = "" |
||||
|
layout = None |
||||
|
form_tag = True |
||||
|
form_error_title = None |
||||
|
formset_error_title = None |
||||
|
form_show_errors = True |
||||
|
render_unmentioned_fields = False |
||||
|
render_hidden_fields = False |
||||
|
render_required_fields = False |
||||
|
_help_text_inline = False |
||||
|
_error_text_inline = True |
||||
|
html5_required = False |
||||
|
form_show_labels = True |
||||
|
template = None |
||||
|
field_template = None |
||||
|
disable_csrf = False |
||||
|
use_custom_control = True |
||||
|
label_class = "" |
||||
|
field_class = "" |
||||
|
include_media = True |
||||
|
|
||||
|
def __init__(self, form=None): |
||||
|
self.attrs = {} |
||||
|
self.inputs = [] |
||||
|
|
||||
|
if form is not None: |
||||
|
self.form = form |
||||
|
self.layout = self.build_default_layout(form) |
||||
|
|
||||
|
def build_default_layout(self, form): |
||||
|
return Layout(*form.fields.keys()) |
||||
|
|
||||
|
@property |
||||
|
def form_method(self): |
||||
|
return self._form_method |
||||
|
|
||||
|
@form_method.setter |
||||
|
def form_method(self, method): |
||||
|
if method.lower() not in ("get", "post"): |
||||
|
raise FormHelpersException( |
||||
|
"Only GET and POST are valid in the \ |
||||
|
form_method helper attribute" |
||||
|
) |
||||
|
|
||||
|
self._form_method = method.lower() |
||||
|
|
||||
|
@property |
||||
|
def form_action(self): |
||||
|
try: |
||||
|
return reverse(self._form_action) |
||||
|
except NoReverseMatch: |
||||
|
return self._form_action |
||||
|
|
||||
|
@form_action.setter |
||||
|
def form_action(self, action): |
||||
|
self._form_action = action |
||||
|
|
||||
|
@property |
||||
|
def form_style(self): |
||||
|
if self._form_style == "default": |
||||
|
return "" |
||||
|
|
||||
|
if self._form_style == "inline": |
||||
|
return "inlineLabels" |
||||
|
|
||||
|
@form_style.setter |
||||
|
def form_style(self, style): |
||||
|
if style.lower() not in ("default", "inline"): |
||||
|
raise FormHelpersException( |
||||
|
"Only default and inline are valid in the \ |
||||
|
form_style helper attribute" |
||||
|
) |
||||
|
|
||||
|
self._form_style = style.lower() |
||||
|
|
||||
|
@property |
||||
|
def help_text_inline(self): |
||||
|
return self._help_text_inline |
||||
|
|
||||
|
@help_text_inline.setter |
||||
|
def help_text_inline(self, flag): |
||||
|
self._help_text_inline = flag |
||||
|
self._error_text_inline = not flag |
||||
|
|
||||
|
@property |
||||
|
def error_text_inline(self): |
||||
|
return self._error_text_inline |
||||
|
|
||||
|
@error_text_inline.setter |
||||
|
def error_text_inline(self, flag): |
||||
|
self._error_text_inline = flag |
||||
|
self._help_text_inline = not flag |
||||
|
|
||||
|
def add_input(self, input_object): |
||||
|
self.inputs.append(input_object) |
||||
|
|
||||
|
def add_layout(self, layout): |
||||
|
self.layout = layout |
||||
|
|
||||
|
def render_layout(self, form, context, template_pack=TEMPLATE_PACK): |
||||
|
""" |
||||
|
Returns safe html of the rendering of the layout |
||||
|
""" |
||||
|
form.rendered_fields = set() |
||||
|
form.crispy_field_template = self.field_template |
||||
|
|
||||
|
# This renders the specified Layout strictly |
||||
|
html = self.layout.render(form, self.form_style, context, template_pack=template_pack) |
||||
|
|
||||
|
# Rendering some extra fields if specified |
||||
|
if self.render_unmentioned_fields or self.render_hidden_fields or self.render_required_fields: |
||||
|
fields = tuple(form.fields.keys()) |
||||
|
left_fields_to_render = list_difference(fields, form.rendered_fields) |
||||
|
for field in left_fields_to_render: |
||||
|
if ( |
||||
|
self.render_unmentioned_fields |
||||
|
or (self.render_hidden_fields and form.fields[field].widget.is_hidden) |
||||
|
or (self.render_required_fields and form.fields[field].widget.is_required) |
||||
|
): |
||||
|
html += render_field(field, form, self.form_style, context, template_pack=template_pack) |
||||
|
|
||||
|
return mark_safe(html) |
||||
|
|
||||
|
def get_attributes(self, template_pack=TEMPLATE_PACK): # noqa: C901 |
||||
|
""" |
||||
|
Used by crispy_forms_tags to get helper attributes |
||||
|
""" |
||||
|
items = { |
||||
|
"disable_csrf": self.disable_csrf, |
||||
|
"error_text_inline": self.error_text_inline, |
||||
|
"field_class": self.field_class, |
||||
|
"field_template": self.field_template or "%s/field.html" % template_pack, |
||||
|
"form_method": self.form_method.strip(), |
||||
|
"form_show_errors": self.form_show_errors, |
||||
|
"form_show_labels": self.form_show_labels, |
||||
|
"form_style": self.form_style.strip(), |
||||
|
"form_tag": self.form_tag, |
||||
|
"help_text_inline": self.help_text_inline, |
||||
|
"html5_required": self.html5_required, |
||||
|
"include_media": self.include_media, |
||||
|
"label_class": self.label_class, |
||||
|
"use_custom_control": self.use_custom_control, |
||||
|
} |
||||
|
|
||||
|
if template_pack == "bootstrap4": |
||||
|
if "form-horizontal" in self.form_class.split(): |
||||
|
bootstrap_size_match = re.findall(r"col(-(xl|lg|md|sm))?-(\d+)", self.label_class) |
||||
|
if bootstrap_size_match: |
||||
|
offset_pattern = "offset%s-%s" |
||||
|
items["bootstrap_checkbox_offsets"] = [ |
||||
|
offset_pattern % (m[0], m[-1]) for m in bootstrap_size_match |
||||
|
] |
||||
|
else: |
||||
|
bootstrap_size_match = re.findall(r"col-(lg|md|sm|xs)-(\d+)", self.label_class) |
||||
|
if bootstrap_size_match: |
||||
|
offset_pattern = "col-%s-offset-%s" |
||||
|
items["bootstrap_checkbox_offsets"] = [offset_pattern % m for m in bootstrap_size_match] |
||||
|
|
||||
|
items["attrs"] = {} |
||||
|
if self.attrs: |
||||
|
items["attrs"] = self.attrs.copy() |
||||
|
if self.form_action: |
||||
|
items["attrs"]["action"] = self.form_action.strip() |
||||
|
if self.form_id: |
||||
|
items["attrs"]["id"] = self.form_id.strip() |
||||
|
if self.form_class: |
||||
|
# uni_form TEMPLATE PACK has a uniForm class by default |
||||
|
if template_pack == "uni_form": |
||||
|
items["attrs"]["class"] = "uniForm %s" % self.form_class.strip() |
||||
|
else: |
||||
|
items["attrs"]["class"] = self.form_class.strip() |
||||
|
else: |
||||
|
if template_pack == "uni_form": |
||||
|
items["attrs"]["class"] = self.attrs.get("class", "") + " uniForm" |
||||
|
if self.form_group_wrapper_class: |
||||
|
items["attrs"]["form_group_wrapper_class"] = self.form_group_wrapper_class |
||||
|
|
||||
|
items["flat_attrs"] = flatatt(items["attrs"]) |
||||
|
|
||||
|
if self.inputs: |
||||
|
items["inputs"] = self.inputs |
||||
|
if self.form_error_title: |
||||
|
items["form_error_title"] = self.form_error_title.strip() |
||||
|
if self.formset_error_title: |
||||
|
items["formset_error_title"] = self.formset_error_title.strip() |
||||
|
|
||||
|
for attribute_name, value in self.__dict__.items(): |
||||
|
if ( |
||||
|
attribute_name not in items |
||||
|
and attribute_name not in ["layout", "inputs"] |
||||
|
and not attribute_name.startswith("_") |
||||
|
): |
||||
|
items[attribute_name] = value |
||||
|
|
||||
|
return items |
@ -0,0 +1,491 @@ |
|||||
|
from django.template import Template |
||||
|
from django.template.loader import render_to_string |
||||
|
from django.utils.html import conditional_escape |
||||
|
|
||||
|
from crispy_forms.utils import TEMPLATE_PACK, flatatt, get_template_pack, render_field |
||||
|
|
||||
|
|
||||
|
class TemplateNameMixin: |
||||
|
def get_template_name(self, template_pack): |
||||
|
if "%s" in self.template: |
||||
|
template = self.template % template_pack |
||||
|
else: |
||||
|
template = self.template |
||||
|
|
||||
|
return template |
||||
|
|
||||
|
|
||||
|
class LayoutObject(TemplateNameMixin): |
||||
|
def __getitem__(self, slice): |
||||
|
return self.fields[slice] |
||||
|
|
||||
|
def __setitem__(self, slice, value): |
||||
|
self.fields[slice] = value |
||||
|
|
||||
|
def __delitem__(self, slice): |
||||
|
del self.fields[slice] |
||||
|
|
||||
|
def __len__(self): |
||||
|
return len(self.fields) |
||||
|
|
||||
|
def __getattr__(self, name): |
||||
|
""" |
||||
|
This allows us to access self.fields list methods like append or insert, without |
||||
|
having to declare them one by one |
||||
|
""" |
||||
|
# Check necessary for unpickling, see #107 |
||||
|
if "fields" in self.__dict__ and hasattr(self.fields, name): |
||||
|
return getattr(self.fields, name) |
||||
|
else: |
||||
|
return object.__getattribute__(self, name) |
||||
|
|
||||
|
def get_field_names(self, index=None): |
||||
|
""" |
||||
|
Returns a list of lists, those lists are named pointers. First parameter |
||||
|
is the location of the field, second one the name of the field. Example:: |
||||
|
|
||||
|
[ |
||||
|
[[0,1,2], 'field_name1'], |
||||
|
[[0,3], 'field_name2'] |
||||
|
] |
||||
|
""" |
||||
|
return self.get_layout_objects(str, index=None, greedy=True) |
||||
|
|
||||
|
def get_layout_objects(self, *LayoutClasses, **kwargs): |
||||
|
""" |
||||
|
Returns a list of lists pointing to layout objects of any type matching |
||||
|
`LayoutClasses`:: |
||||
|
|
||||
|
[ |
||||
|
[[0,1,2], 'div'], |
||||
|
[[0,3], 'field_name'] |
||||
|
] |
||||
|
|
||||
|
:param max_level: An integer that indicates max level depth to reach when |
||||
|
traversing a layout. |
||||
|
:param greedy: Boolean that indicates whether to be greedy. If set, max_level |
||||
|
is skipped. |
||||
|
""" |
||||
|
index = kwargs.pop("index", None) |
||||
|
max_level = kwargs.pop("max_level", 0) |
||||
|
greedy = kwargs.pop("greedy", False) |
||||
|
|
||||
|
pointers = [] |
||||
|
|
||||
|
if index is not None and not isinstance(index, list): |
||||
|
index = [index] |
||||
|
elif index is None: |
||||
|
index = [] |
||||
|
|
||||
|
for i, layout_object in enumerate(self.fields): |
||||
|
if isinstance(layout_object, LayoutClasses): |
||||
|
if len(LayoutClasses) == 1 and LayoutClasses[0] == str: |
||||
|
pointers.append([index + [i], layout_object]) |
||||
|
else: |
||||
|
pointers.append([index + [i], layout_object.__class__.__name__.lower()]) |
||||
|
|
||||
|
# If it's a layout object and we haven't reached the max depth limit or greedy |
||||
|
# we recursive call |
||||
|
if hasattr(layout_object, "get_field_names") and (len(index) < max_level or greedy): |
||||
|
new_kwargs = {"index": index + [i], "max_level": max_level, "greedy": greedy} |
||||
|
pointers = pointers + layout_object.get_layout_objects(*LayoutClasses, **new_kwargs) |
||||
|
|
||||
|
return pointers |
||||
|
|
||||
|
def get_rendered_fields(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
return "".join( |
||||
|
render_field(field, form, form_style, context, template_pack=template_pack, **kwargs) |
||||
|
for field in self.fields |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class Layout(LayoutObject): |
||||
|
""" |
||||
|
Form Layout. It is conformed by Layout objects: `Fieldset`, `Row`, `Column`, `MultiField`, |
||||
|
`HTML`, `ButtonHolder`, `Button`, `Hidden`, `Reset`, `Submit` and fields. Form fields |
||||
|
have to be strings. |
||||
|
Layout objects `Fieldset`, `Row`, `Column`, `MultiField` and `ButtonHolder` can hold other |
||||
|
Layout objects within. Though `ButtonHolder` should only hold `HTML` and BaseInput |
||||
|
inherited classes: `Button`, `Hidden`, `Reset` and `Submit`. |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
helper.layout = Layout( |
||||
|
Fieldset('Company data', |
||||
|
'is_company' |
||||
|
), |
||||
|
Fieldset(_('Contact details'), |
||||
|
'email', |
||||
|
Row('password1', 'password2'), |
||||
|
'first_name', |
||||
|
'last_name', |
||||
|
HTML('<img src="/media/somepicture.jpg"/>'), |
||||
|
'company' |
||||
|
), |
||||
|
ButtonHolder( |
||||
|
Submit('Save', 'Save', css_class='button white'), |
||||
|
), |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, *fields): |
||||
|
self.fields = list(fields) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
return self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) |
||||
|
|
||||
|
|
||||
|
class ButtonHolder(LayoutObject): |
||||
|
""" |
||||
|
Layout object. It wraps fields in a <div class="buttonHolder"> |
||||
|
|
||||
|
This is where you should put Layout objects that render to form buttons like Submit. |
||||
|
It should only hold `HTML` and `BaseInput` inherited objects. |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
ButtonHolder( |
||||
|
HTML(<span style="display: hidden;">Information Saved</span>), |
||||
|
Submit('Save', 'Save') |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/buttonholder.html" |
||||
|
|
||||
|
def __init__(self, *fields, **kwargs): |
||||
|
self.fields = list(fields) |
||||
|
self.css_class = kwargs.get("css_class", None) |
||||
|
self.css_id = kwargs.get("css_id", None) |
||||
|
self.template = kwargs.get("template", self.template) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
html = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) |
||||
|
|
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"buttonholder": self, "fields_output": html}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class BaseInput(TemplateNameMixin): |
||||
|
""" |
||||
|
A base class to reduce the amount of code in the Input classes. |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/baseinput.html" |
||||
|
|
||||
|
def __init__(self, name, value, **kwargs): |
||||
|
self.name = name |
||||
|
self.value = value |
||||
|
self.id = kwargs.pop("css_id", "") |
||||
|
self.attrs = {} |
||||
|
|
||||
|
if "css_class" in kwargs: |
||||
|
self.field_classes += " %s" % kwargs.pop("css_class") |
||||
|
|
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.flat_attrs = flatatt(kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
""" |
||||
|
Renders an `<input />` if container is used as a Layout object. |
||||
|
Input button value can be a variable in context. |
||||
|
""" |
||||
|
self.value = Template(str(self.value)).render(context) |
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"input": self}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class Submit(BaseInput): |
||||
|
""" |
||||
|
Used to create a Submit button descriptor for the {% crispy %} template tag:: |
||||
|
|
||||
|
submit = Submit('Search the Site', 'search this site') |
||||
|
|
||||
|
.. note:: The first argument is also slugified and turned into the id for the submit button. |
||||
|
""" |
||||
|
|
||||
|
input_type = "submit" |
||||
|
|
||||
|
def __init__(self, *args, **kwargs): |
||||
|
self.field_classes = "submit submitButton" if get_template_pack() == "uni_form" else "btn btn-primary" |
||||
|
super().__init__(*args, **kwargs) |
||||
|
|
||||
|
|
||||
|
class Button(BaseInput): |
||||
|
""" |
||||
|
Used to create a Submit input descriptor for the {% crispy %} template tag:: |
||||
|
|
||||
|
button = Button('Button 1', 'Press Me!') |
||||
|
|
||||
|
.. note:: The first argument is also slugified and turned into the id for the button. |
||||
|
""" |
||||
|
|
||||
|
input_type = "button" |
||||
|
|
||||
|
def __init__(self, *args, **kwargs): |
||||
|
self.field_classes = "button" if get_template_pack() == "uni_form" else "btn" |
||||
|
super().__init__(*args, **kwargs) |
||||
|
|
||||
|
|
||||
|
class Hidden(BaseInput): |
||||
|
""" |
||||
|
Used to create a Hidden input descriptor for the {% crispy %} template tag. |
||||
|
""" |
||||
|
|
||||
|
input_type = "hidden" |
||||
|
field_classes = "hidden" |
||||
|
|
||||
|
|
||||
|
class Reset(BaseInput): |
||||
|
""" |
||||
|
Used to create a Reset button input descriptor for the {% crispy %} template tag:: |
||||
|
|
||||
|
reset = Reset('Reset This Form', 'Revert Me!') |
||||
|
|
||||
|
.. note:: The first argument is also slugified and turned into the id for the reset. |
||||
|
""" |
||||
|
|
||||
|
input_type = "reset" |
||||
|
|
||||
|
def __init__(self, *args, **kwargs): |
||||
|
self.field_classes = "reset resetButton" if get_template_pack() == "uni_form" else "btn btn-inverse" |
||||
|
super().__init__(*args, **kwargs) |
||||
|
|
||||
|
|
||||
|
class Fieldset(LayoutObject): |
||||
|
""" |
||||
|
Layout object. It wraps fields in a <fieldset> |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
Fieldset("Text for the legend", |
||||
|
'form_field_1', |
||||
|
'form_field_2' |
||||
|
) |
||||
|
|
||||
|
The first parameter is the text for the fieldset legend. This text is context aware, |
||||
|
so you can do things like:: |
||||
|
|
||||
|
Fieldset("Data for {{ user.username }}", |
||||
|
'form_field_1', |
||||
|
'form_field_2' |
||||
|
) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/fieldset.html" |
||||
|
|
||||
|
def __init__(self, legend, *fields, **kwargs): |
||||
|
self.fields = list(fields) |
||||
|
self.legend = legend |
||||
|
self.css_class = kwargs.pop("css_class", "") |
||||
|
self.css_id = kwargs.pop("css_id", None) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.flat_attrs = flatatt(kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) |
||||
|
|
||||
|
legend = "" |
||||
|
if self.legend: |
||||
|
legend = "%s" % Template(str(self.legend)).render(context) |
||||
|
|
||||
|
template = self.get_template_name(template_pack) |
||||
|
return render_to_string( |
||||
|
template, {"fieldset": self, "legend": legend, "fields": fields, "form_style": form_style} |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class MultiField(LayoutObject): |
||||
|
"""MultiField container. Renders to a MultiField <div>""" |
||||
|
|
||||
|
template = "%s/layout/multifield.html" |
||||
|
field_template = "%s/multifield.html" |
||||
|
|
||||
|
def __init__(self, label, *fields, **kwargs): |
||||
|
self.fields = list(fields) |
||||
|
self.label_html = label |
||||
|
self.label_class = kwargs.pop("label_class", "blockLabel") |
||||
|
self.css_class = kwargs.pop("css_class", "ctrlHolder") |
||||
|
self.css_id = kwargs.pop("css_id", None) |
||||
|
self.help_text = kwargs.pop("help_text", None) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.field_template = kwargs.pop("field_template", self.field_template) |
||||
|
self.flat_attrs = flatatt(kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
# If a field within MultiField contains errors |
||||
|
if context["form_show_errors"]: |
||||
|
for field in map(lambda pointer: pointer[1], self.get_field_names()): |
||||
|
if field in form.errors: |
||||
|
self.css_class += " error" |
||||
|
|
||||
|
field_template = self.field_template % template_pack |
||||
|
fields_output = self.get_rendered_fields( |
||||
|
form, |
||||
|
form_style, |
||||
|
context, |
||||
|
template_pack, |
||||
|
template=field_template, |
||||
|
labelclass=self.label_class, |
||||
|
layout_object=self, |
||||
|
**kwargs, |
||||
|
) |
||||
|
|
||||
|
template = self.get_template_name(template_pack) |
||||
|
context.update({"multifield": self, "fields_output": fields_output}) |
||||
|
|
||||
|
return render_to_string(template, context.flatten()) |
||||
|
|
||||
|
|
||||
|
class Div(LayoutObject): |
||||
|
""" |
||||
|
Layout object. It wraps fields in a <div> |
||||
|
|
||||
|
You can set `css_id` for a DOM id and `css_class` for a DOM class. Example:: |
||||
|
|
||||
|
Div('form_field_1', 'form_field_2', css_id='div-example', css_class='divs') |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/div.html" |
||||
|
|
||||
|
def __init__(self, *fields, **kwargs): |
||||
|
self.fields = list(fields) |
||||
|
|
||||
|
if hasattr(self, "css_class") and "css_class" in kwargs: |
||||
|
self.css_class += " %s" % kwargs.pop("css_class") |
||||
|
if not hasattr(self, "css_class"): |
||||
|
self.css_class = kwargs.pop("css_class", None) |
||||
|
|
||||
|
self.css_id = kwargs.pop("css_id", "") |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.flat_attrs = flatatt(kwargs) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) |
||||
|
|
||||
|
template = self.get_template_name(template_pack) |
||||
|
return render_to_string(template, {"div": self, "fields": fields}) |
||||
|
|
||||
|
|
||||
|
class Row(Div): |
||||
|
""" |
||||
|
Layout object. It wraps fields in a div whose default class is "formRow". Example:: |
||||
|
|
||||
|
Row('form_field_1', 'form_field_2', 'form_field_3') |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/row.html" |
||||
|
|
||||
|
|
||||
|
class Column(Div): |
||||
|
""" |
||||
|
Layout object. It wraps fields in a div so the wrapper can be used as a column. Example:: |
||||
|
|
||||
|
Column('form_field_1', 'form_field_2') |
||||
|
|
||||
|
Depending on the template, css class associated to the div is formColumn, row, or nothing. For this last case, you |
||||
|
must provide css classes. Example:: |
||||
|
|
||||
|
Column('form_field_1', 'form_field_2', css_class='col-xs-6',) |
||||
|
""" |
||||
|
|
||||
|
template = "%s/layout/column.html" |
||||
|
|
||||
|
|
||||
|
class HTML: |
||||
|
""" |
||||
|
Layout object. It can contain pure HTML and it has access to the whole |
||||
|
context of the page where the form is being rendered. |
||||
|
|
||||
|
Examples:: |
||||
|
|
||||
|
HTML("{% if saved %}Data saved{% endif %}") |
||||
|
HTML('<input type="hidden" name="{{ step_field }}" value="{{ step0 }}" />') |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, html): |
||||
|
self.html = html |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): |
||||
|
return Template(str(self.html)).render(context) |
||||
|
|
||||
|
|
||||
|
class Field(LayoutObject): |
||||
|
""" |
||||
|
Layout object, It contains one field name, and you can add attributes to it easily. |
||||
|
For setting class attributes, you need to use `css_class`, as `class` is a Python keyword. |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
Field('field_name', style="color: #333;", css_class="whatever", id="field_name") |
||||
|
""" |
||||
|
|
||||
|
template = "%s/field.html" |
||||
|
|
||||
|
def __init__(self, *args, **kwargs): |
||||
|
self.fields = list(args) |
||||
|
|
||||
|
if not hasattr(self, "attrs"): |
||||
|
self.attrs = {} |
||||
|
else: |
||||
|
# Make sure shared state is not edited. |
||||
|
self.attrs = self.attrs.copy() |
||||
|
|
||||
|
if "css_class" in kwargs: |
||||
|
if "class" in self.attrs: |
||||
|
self.attrs["class"] += " %s" % kwargs.pop("css_class") |
||||
|
else: |
||||
|
self.attrs["class"] = kwargs.pop("css_class") |
||||
|
|
||||
|
self.wrapper_class = kwargs.pop("wrapper_class", None) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
|
||||
|
# We use kwargs as HTML attributes, turning data_id='test' into data-id='test' |
||||
|
self.attrs.update({k.replace("_", "-"): conditional_escape(v) for k, v in kwargs.items()}) |
||||
|
|
||||
|
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs): |
||||
|
if extra_context is None: |
||||
|
extra_context = {} |
||||
|
if hasattr(self, "wrapper_class"): |
||||
|
extra_context["wrapper_class"] = self.wrapper_class |
||||
|
|
||||
|
template = self.get_template_name(template_pack) |
||||
|
|
||||
|
return self.get_rendered_fields( |
||||
|
form, |
||||
|
form_style, |
||||
|
context, |
||||
|
template_pack, |
||||
|
template=template, |
||||
|
attrs=self.attrs, |
||||
|
extra_context=extra_context, |
||||
|
**kwargs, |
||||
|
) |
||||
|
|
||||
|
|
||||
|
class MultiWidgetField(Field): |
||||
|
""" |
||||
|
Layout object. For fields with :class:`~django.forms.MultiWidget` as `widget`, you can pass |
||||
|
additional attributes to each widget. |
||||
|
|
||||
|
Example:: |
||||
|
|
||||
|
MultiWidgetField( |
||||
|
'multiwidget_field_name', |
||||
|
attrs=( |
||||
|
{'style': 'width: 30px;'}, |
||||
|
{'class': 'second_widget_class'} |
||||
|
), |
||||
|
) |
||||
|
|
||||
|
.. note:: To override widget's css class use ``class`` not ``css_class``. |
||||
|
""" |
||||
|
|
||||
|
def __init__(self, *args, **kwargs): |
||||
|
self.fields = list(args) |
||||
|
self.attrs = kwargs.pop("attrs", {}) |
||||
|
self.template = kwargs.pop("template", self.template) |
||||
|
self.wrapper_class = kwargs.pop("wrapper_class", None) |
@ -0,0 +1,156 @@ |
|||||
|
from crispy_forms.bootstrap import Container |
||||
|
from crispy_forms.exceptions import DynamicError |
||||
|
from crispy_forms.layout import Fieldset, MultiField |
||||
|
|
||||
|
|
||||
|
class LayoutSlice: |
||||
|
# List of layout objects that need args passed first before fields |
||||
|
args_first = (Fieldset, MultiField, Container) |
||||
|
|
||||
|
def __init__(self, layout, key): |
||||
|
self.layout = layout |
||||
|
if isinstance(key, int): |
||||
|
self.slice = slice(key, key + 1, 1) |
||||
|
else: |
||||
|
self.slice = key |
||||
|
|
||||
|
def wrapped_object(self, LayoutClass, fields, *args, **kwargs): |
||||
|
""" |
||||
|
Returns a layout object of type `LayoutClass` with `args` and `kwargs` that |
||||
|
wraps `fields` inside. |
||||
|
""" |
||||
|
if args: |
||||
|
if isinstance(fields, list): |
||||
|
fields = tuple(fields) |
||||
|
else: |
||||
|
fields = (fields,) |
||||
|
|
||||
|
if LayoutClass in self.args_first: |
||||
|
arguments = args + fields |
||||
|
else: |
||||
|
arguments = fields + args |
||||
|
|
||||
|
return LayoutClass(*arguments, **kwargs) |
||||
|
else: |
||||
|
if isinstance(fields, list): |
||||
|
return LayoutClass(*fields, **kwargs) |
||||
|
else: |
||||
|
return LayoutClass(fields, **kwargs) |
||||
|
|
||||
|
def pre_map(self, function): |
||||
|
""" |
||||
|
Iterates over layout objects pointed in `self.slice` executing `function` on them. |
||||
|
It passes `function` penultimate layout object and the position where to find last one |
||||
|
""" |
||||
|
if isinstance(self.slice, slice): |
||||
|
for i in range(*self.slice.indices(len(self.layout.fields))): |
||||
|
function(self.layout, i) |
||||
|
|
||||
|
elif isinstance(self.slice, list): |
||||
|
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']] |
||||
|
for pointer in self.slice: |
||||
|
position = pointer[0] |
||||
|
|
||||
|
# If it's pointing first level |
||||
|
if len(position) == 1: |
||||
|
function(self.layout, position[-1]) |
||||
|
else: |
||||
|
layout_object = self.layout.fields[position[0]] |
||||
|
for i in position[1:-1]: |
||||
|
layout_object = layout_object.fields[i] |
||||
|
|
||||
|
try: |
||||
|
function(layout_object, position[-1]) |
||||
|
except IndexError: |
||||
|
# We could avoid this exception, recalculating pointers. |
||||
|
# However this case is most of the time an undesired behavior |
||||
|
raise DynamicError( |
||||
|
"Trying to wrap a field within an already wrapped field, \ |
||||
|
recheck your filter or layout" |
||||
|
) |
||||
|
|
||||
|
def wrap(self, LayoutClass, *args, **kwargs): |
||||
|
""" |
||||
|
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with |
||||
|
`args` and `kwargs` passed. |
||||
|
""" |
||||
|
|
||||
|
def wrap_object(layout_object, j): |
||||
|
layout_object.fields[j] = self.wrapped_object(LayoutClass, layout_object.fields[j], *args, **kwargs) |
||||
|
|
||||
|
self.pre_map(wrap_object) |
||||
|
|
||||
|
def wrap_once(self, LayoutClass, *args, **kwargs): |
||||
|
""" |
||||
|
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with |
||||
|
`args` and `kwargs` passed, unless layout object's parent is already a subclass of |
||||
|
`LayoutClass`. |
||||
|
""" |
||||
|
|
||||
|
def wrap_object_once(layout_object, j): |
||||
|
if not isinstance(layout_object, LayoutClass): |
||||
|
layout_object.fields[j] = self.wrapped_object(LayoutClass, layout_object.fields[j], *args, **kwargs) |
||||
|
|
||||
|
self.pre_map(wrap_object_once) |
||||
|
|
||||
|
def wrap_together(self, LayoutClass, *args, **kwargs): |
||||
|
""" |
||||
|
Wraps all layout objects pointed in `self.slice` together under a `LayoutClass` |
||||
|
instance with `args` and `kwargs` passed. |
||||
|
""" |
||||
|
if isinstance(self.slice, slice): |
||||
|
# The start of the slice is replaced |
||||
|
start = self.slice.start if self.slice.start is not None else 0 |
||||
|
self.layout.fields[start] = self.wrapped_object( |
||||
|
LayoutClass, self.layout.fields[self.slice], *args, **kwargs |
||||
|
) |
||||
|
|
||||
|
# The rest of places of the slice are removed, as they are included in the previous |
||||
|
for i in reversed(range(*self.slice.indices(len(self.layout.fields)))): |
||||
|
if i != start: |
||||
|
del self.layout.fields[i] |
||||
|
|
||||
|
elif isinstance(self.slice, list): |
||||
|
raise DynamicError("wrap_together doesn't work with filter, only with [] operator") |
||||
|
|
||||
|
def map(self, function): |
||||
|
""" |
||||
|
Iterates over layout objects pointed in `self.slice` executing `function` on them |
||||
|
It passes `function` last layout object |
||||
|
""" |
||||
|
if isinstance(self.slice, slice): |
||||
|
for i in range(*self.slice.indices(len(self.layout.fields))): |
||||
|
function(self.layout.fields[i]) |
||||
|
|
||||
|
elif isinstance(self.slice, list): |
||||
|
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']] |
||||
|
for pointer in self.slice: |
||||
|
position = pointer[0] |
||||
|
|
||||
|
layout_object = self.layout.fields[position[0]] |
||||
|
for i in position[1:]: |
||||
|
previous_layout_object = layout_object |
||||
|
layout_object = layout_object.fields[i] |
||||
|
|
||||
|
# If update_attrs is applied to a string, we call to its wrapping layout object |
||||
|
if function.__name__ == "update_attrs" and isinstance(layout_object, str): |
||||
|
function(previous_layout_object) |
||||
|
else: |
||||
|
function(layout_object) |
||||
|
|
||||
|
def update_attributes(self, **original_kwargs): |
||||
|
""" |
||||
|
Updates attributes of every layout object pointed in `self.slice` using kwargs |
||||
|
""" |
||||
|
|
||||
|
def update_attrs(layout_object): |
||||
|
kwargs = original_kwargs.copy() |
||||
|
if hasattr(layout_object, "attrs"): |
||||
|
if "css_class" in kwargs: |
||||
|
if "class" in layout_object.attrs: |
||||
|
layout_object.attrs["class"] += " %s" % kwargs.pop("css_class") |
||||
|
else: |
||||
|
layout_object.attrs["class"] = kwargs.pop("css_class") |
||||
|
layout_object.attrs.update(kwargs) |
||||
|
|
||||
|
self.map(update_attrs) |
@ -0,0 +1,10 @@ |
|||||
|
<div class="accordion-group"> |
||||
|
<div class="accordion-heading"> |
||||
|
<a class="accordion-toggle" data-toggle="collapse" data-parent="#{{ div.data_parent }}" href="#{{ div.css_id }}">{{ div.name }}</a> |
||||
|
</div> |
||||
|
<div id="{{ div.css_id }}" class="accordion-body collapse{% if div.active %} in{% endif %}" > |
||||
|
<div class="accordion-inner"> |
||||
|
{{ fields|safe }} |
||||
|
</div> |
||||
|
</div> |
||||
|
</div> |
@ -0,0 +1,3 @@ |
|||||
|
<div class="accordion" id="{{ accordion.css_id }}"> |
||||
|
{{ content|safe }} |
||||
|
</div> |
@ -0,0 +1,22 @@ |
|||||
|
{% for fieldset in form.fieldsets %} |
||||
|
<fieldset class="fieldset-{{ forloop.counter }} {{ fieldset.classes }}"> |
||||
|
{% if fieldset.legend %} |
||||
|
<legend>{{ fieldset.legend }}</legend> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if fieldset.description %} |
||||
|
<p class="description">{{ fieldset.description }}</p> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% for field in fieldset %} |
||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
{% include "bootstrap/field.html" %} |
||||
|
{% endif %} |
||||
|
{% endfor %} |
||||
|
{% if not forloop.last or not fieldset_open %} |
||||
|
</fieldset> |
||||
|
{% endif %} |
||||
|
{% endfor %} |
||||
|
|
@ -0,0 +1,9 @@ |
|||||
|
{% if form.form_html %} |
||||
|
{% if include_media %}{{ form.media }}{% endif %} |
||||
|
{% if form_show_errors %} |
||||
|
{% include "bootstrap/errors.html" %} |
||||
|
{% endif %} |
||||
|
{{ form.form_html }} |
||||
|
{% else %} |
||||
|
{% include "bootstrap/uni_form.html" %} |
||||
|
{% endif %} |
@ -0,0 +1,8 @@ |
|||||
|
{% if form.non_field_errors %} |
||||
|
<div class="alert alert-block alert-error"> |
||||
|
{% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %} |
||||
|
<ul> |
||||
|
{{ form.non_field_errors|unordered_list }} |
||||
|
</ul> |
||||
|
</div> |
||||
|
{% endif %} |
@ -0,0 +1,9 @@ |
|||||
|
{% if formset.non_form_errors %} |
||||
|
<div class="alert alert-block alert-error"> |
||||
|
{% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %} |
||||
|
<ul> |
||||
|
{{ formset.non_form_errors|unordered_list }} |
||||
|
</ul> |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
|
@ -0,0 +1,36 @@ |
|||||
|
{% load crispy_forms_field %} |
||||
|
|
||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
<{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" class="control-group{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> |
||||
|
{% if field.label and not field|is_checkbox and form_show_labels %} |
||||
|
<label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field|is_checkboxselectmultiple %} |
||||
|
{% include 'bootstrap/layout/checkboxselectmultiple.html' %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field|is_radioselect %} |
||||
|
{% include 'bootstrap/layout/radioselect.html' %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if not field|is_checkboxselectmultiple and not field|is_radioselect %} |
||||
|
<div class="controls"> |
||||
|
{% if field|is_checkbox and form_show_labels %} |
||||
|
<label for="{{ field.id_for_label }}" class="checkbox {% if field.field.required %}requiredField{% endif %}"> |
||||
|
{% crispy_field field %} |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %} |
||||
|
{% else %} |
||||
|
{% crispy_field field %} |
||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %} |
||||
|
{% endif %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
</{% if tag %}{{ tag }}{% else %}div{% endif %}> |
||||
|
{% endif %} |
@ -0,0 +1,4 @@ |
|||||
|
<div{% if alert.css_id %} id="{{ alert.css_id }}"{% endif %}{% if alert.css_class %} class="{{ alert.css_class }}"{% endif %}> |
||||
|
{% if dismiss %}<button type="button" class="close" data-dismiss="alert">×</button>{% endif %} |
||||
|
{{ content|safe }} |
||||
|
</div> |
@ -0,0 +1,9 @@ |
|||||
|
<input type="{{ input.input_type }}" |
||||
|
name="{% if input.name|wordcount > 1 %}{{ input.name|slugify }}{% else %}{{ input.name }}{% endif %}" |
||||
|
value="{{ input.value }}" |
||||
|
{% if input.input_type != "hidden" %} |
||||
|
class="{{ input.field_classes }}" |
||||
|
id="{% if input.id %}{{ input.id }}{% else %}{{ input.input_type }}-id-{{ input.name|slugify }}{% endif %}" |
||||
|
{% endif %} |
||||
|
{{ input.flat_attrs|safe }} |
||||
|
/> |
@ -0,0 +1 @@ |
|||||
|
<button {{ button.flat_attrs|safe }}>{{ button.content|safe }}</button> |
@ -0,0 +1,4 @@ |
|||||
|
<div {% if buttonholder.css_id %}id="{{ buttonholder.css_id }}"{% endif %} |
||||
|
class="buttonHolder{% if buttonholder.css_class %} {{ buttonholder.css_class }}{% endif %}"> |
||||
|
{{ fields_output|safe }} |
||||
|
</div> |
@ -0,0 +1,14 @@ |
|||||
|
{% load crispy_forms_filters %} |
||||
|
{% load l10n %} |
||||
|
|
||||
|
<div class="controls"{% if flat_attrs %} {{ flat_attrs|safe }}{% endif %}> |
||||
|
{% include 'bootstrap/layout/field_errors_block.html' %} |
||||
|
|
||||
|
{% for choice in field.field.choices %} |
||||
|
<label class="checkbox{% if inline_class %} {{ inline_class }}{% endif %}" for="id_{{ field.html_name }}_{{ forloop.counter0 }}"> |
||||
|
<input type="checkbox"{% if choice.0 in field.value or choice.0|stringformat:"s" in field.value or choice.0|stringformat:"s" == field.value|default_if_none:""|stringformat:"s" %} checked{% endif %} name="{{ field.html_name }}" id="id_{{ field.html_name }}_{{ forloop.counter0 }}" value="{{ choice.0|unlocalize }}" {% if field.field.disabled %}disabled="true"{% endif %} {{ field.field.widget.attrs|flatatt }}>{{ choice.1|unlocalize }} |
||||
|
</label> |
||||
|
{% endfor %} |
||||
|
|
||||
|
{% include 'bootstrap/layout/help_text.html' %} |
||||
|
</div> |
@ -0,0 +1,14 @@ |
|||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> |
||||
|
|
||||
|
{% if field.label %} |
||||
|
<label for="{{ field.auto_id }}" class="control-label{% if field.field.required %} requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% include 'bootstrap/layout/checkboxselectmultiple.html' %} |
||||
|
</div> |
||||
|
{% endif %} |
@ -0,0 +1,3 @@ |
|||||
|
<div {% if div.css_id %}id="{{ div.css_id }}"{% endif %} class="{{ div.css_class|default:'' }}" {{ div.flat_attrs|safe }}> |
||||
|
{{ fields|safe }} |
||||
|
</div> |
@ -0,0 +1,4 @@ |
|||||
|
<div {% if div.css_id %}id="{{ div.css_id }}"{% endif %} |
||||
|
{% if div.css_class %}class="{{ div.css_class }}"{% endif %} {{ div.flat_attrs|safe }}> |
||||
|
{{ fields|safe }} |
||||
|
</div> |
@ -0,0 +1,5 @@ |
|||||
|
{% if form_show_errors and field.errors %} |
||||
|
{% for error in field.errors %} |
||||
|
<span id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="help-inline"><strong>{{ error }}</strong></span> |
||||
|
{% endfor %} |
||||
|
{% endif %} |
@ -0,0 +1,5 @@ |
|||||
|
{% if form_show_errors and field.errors %} |
||||
|
{% for error in field.errors %} |
||||
|
<p id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="help-block"><strong>{{ error }}</strong></p> |
||||
|
{% endfor %} |
||||
|
{% endif %} |
@ -0,0 +1,17 @@ |
|||||
|
{% load crispy_forms_field %} |
||||
|
|
||||
|
<div{% if div.css_id %} id="{{ div.css_id }}"{% endif %} class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}{% if div.css_class %} {{ div.css_class }}{% endif %}" {{ div.flat_attrs|safe }}> |
||||
|
{% if field.label and form_show_labels %} |
||||
|
<label for="{{ field.id_for_label }}" class="control-label{% if field.field.required %} requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
<div class="controls"> |
||||
|
<div class="input-append"> |
||||
|
{% crispy_field field %} |
||||
|
{{ buttons|safe }} |
||||
|
</div> |
||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %} |
||||
|
</div> |
||||
|
</div> |
@ -0,0 +1,6 @@ |
|||||
|
<fieldset {% if fieldset.css_id %}id="{{ fieldset.css_id }}"{% endif %} |
||||
|
{% if fieldset.css_class or form_style %}class="{{ fieldset.css_class }} {{ form_style }}"{% endif %} |
||||
|
{{ fieldset.flat_attrs|safe }}> |
||||
|
{% if legend %}<legend>{{ legend|safe }}</legend>{% endif %} |
||||
|
{{ fields|safe }} |
||||
|
</fieldset> |
@ -0,0 +1,3 @@ |
|||||
|
<div{% if formactions.attrs %} {{ formactions.flat_attrs|safe }}{% endif %} class="form-actions"> |
||||
|
{{ fields_output|safe }} |
||||
|
</div> |
@ -0,0 +1,7 @@ |
|||||
|
{% if field.help_text %} |
||||
|
{% if help_text_inline %} |
||||
|
<span id="hint_{{ field.auto_id }}" class="help-inline">{{ field.help_text|safe }}</span> |
||||
|
{% else %} |
||||
|
<p id="hint_{{ field.auto_id }}" class="help-block">{{ field.help_text|safe }}</p> |
||||
|
{% endif %} |
||||
|
{% endif %} |
@ -0,0 +1,13 @@ |
|||||
|
{% if help_text_inline and not error_text_inline %} |
||||
|
{% include 'bootstrap/layout/help_text.html' %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if error_text_inline %} |
||||
|
{% include 'bootstrap/layout/field_errors.html' %} |
||||
|
{% else %} |
||||
|
{% include 'bootstrap/layout/field_errors_block.html' %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if not help_text_inline %} |
||||
|
{% include 'bootstrap/layout/help_text.html' %} |
||||
|
{% endif %} |
@ -0,0 +1,27 @@ |
|||||
|
{% load crispy_forms_field %} |
||||
|
|
||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
|
||||
|
{% if field.label %} |
||||
|
<label for="{{ field.id_for_label }}"{% if labelclass %} class="{{ labelclass }}"{% endif %}> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field|is_checkbox %} |
||||
|
{% crispy_field field %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field.label %} |
||||
|
{{ field.label }} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if not field|is_checkbox %} |
||||
|
{% crispy_field field %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field.label %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% endif %} |
@ -0,0 +1,24 @@ |
|||||
|
{% load crispy_forms_field %} |
||||
|
|
||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> |
||||
|
|
||||
|
{% if field.label and form_show_labels %} |
||||
|
<label for="{{ field.id_for_label }}" class="control-label{% if field.field.required %} requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
<div class="controls"> |
||||
|
<div class="{% if crispy_prepended_text %}input-prepend{% endif %} {% if crispy_appended_text %}input-append{% endif %}"> |
||||
|
{% if crispy_prepended_text %}<span class="{% if not field|is_select %}add-on{% endif %}{% if active %} active{% endif %}">{{ crispy_prepended_text|safe }}</span>{% endif %} |
||||
|
{% crispy_field field %} |
||||
|
{% if crispy_appended_text %}<span class="{% if not field|is_select %}add-on{% endif %}{% if active %} active{% endif %}">{{ crispy_appended_text|safe }}</span>{% endif %} |
||||
|
</div> |
||||
|
|
||||
|
{% include 'bootstrap/layout/help_text_and_errors.html' %} |
||||
|
</div> |
||||
|
</div> |
||||
|
{% endif %} |
@ -0,0 +1,14 @@ |
|||||
|
{% load crispy_forms_filters %} |
||||
|
{% load l10n %} |
||||
|
|
||||
|
<div class="controls"{% if flat_attrs %} {{ flat_attrs|safe }}{% endif %}> |
||||
|
{% include 'bootstrap/layout/field_errors_block.html' %} |
||||
|
|
||||
|
{% for choice in field.field.choices %} |
||||
|
<label for="id_{{ field.html_name }}_{{ forloop.counter0 }}" class="radio{% if inline_class %} {{ inline_class }}{% endif %}"> |
||||
|
<input type="radio"{% if choice.0|stringformat:"s" == field.value|default_if_none:""|stringformat:"s" %} checked{% endif %} name="{{ field.html_name }}" id="id_{{ field.html_name }}_{{ forloop.counter0 }}" value="{{ choice.0|unlocalize }}" {% if field.field.disabled %}disabled="true"{% endif %} {{ field.field.widget.attrs|flatatt }}>{{ choice.1|unlocalize }} |
||||
|
</label> |
||||
|
{% endfor %} |
||||
|
|
||||
|
{% include 'bootstrap/layout/help_text.html' %} |
||||
|
</div> |
@ -0,0 +1,14 @@ |
|||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> |
||||
|
|
||||
|
{% if field.label %} |
||||
|
<label for="{{ field.auto_id }}" class="control-label{% if field.field.required %} requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% include 'bootstrap/layout/radioselect.html' %} |
||||
|
</div> |
||||
|
{% endif %} |
@ -0,0 +1,3 @@ |
|||||
|
<div {% if div.css_id %}id="{{ div.css_id }}"{% endif %} class="row {{ div.css_class|default:'' }}" {{ div.flat_attrs|safe }}> |
||||
|
{{ fields|safe }} |
||||
|
</div> |
@ -0,0 +1 @@ |
|||||
|
<li class="tab-pane{% if 'active' in link.css_class %} active{% endif %}"><a href="#{{ link.css_id }}" data-toggle="tab">{{ link.name|capfirst }}{% if tab.errors %}!{% endif %}</a></li> |
@ -0,0 +1,6 @@ |
|||||
|
<ul{% if tabs.css_id %} id="{{ tabs.css_id }}"{% endif %} class="nav nav-tabs"> |
||||
|
{{ links|safe }} |
||||
|
</ul> |
||||
|
<div class="tab-content"> |
||||
|
{{ content|safe }} |
||||
|
</div> |
@ -0,0 +1,7 @@ |
|||||
|
<div id="div_{{ field.auto_id }}" class="control-group{% if form_show_errors and field.errors %} error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> |
||||
|
<div class="control-label{% if field.field.required %} requiredField{% endif %}">{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}</div> |
||||
|
<div class="controls"> |
||||
|
<span {{ flat_attrs|safe }}>{% if field.value %}{{ field.value }}{% endif %}</span> |
||||
|
{% include 'bootstrap/layout/help_text.html' %} |
||||
|
</div> |
||||
|
</div> |
@ -0,0 +1,62 @@ |
|||||
|
{% load crispy_forms_tags %} |
||||
|
{% load crispy_forms_utils %} |
||||
|
{% load crispy_forms_field %} |
||||
|
|
||||
|
{% specialspaceless %} |
||||
|
{% if formset_tag %} |
||||
|
<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}> |
||||
|
{% endif %} |
||||
|
{% if formset_method|lower == 'post' and not disable_csrf %} |
||||
|
{% csrf_token %} |
||||
|
{% endif %} |
||||
|
|
||||
|
<div> |
||||
|
{{ formset.management_form|crispy }} |
||||
|
</div> |
||||
|
|
||||
|
<table{% if form_id %} id="{{ form_id }}_table"{% endif%} class="table table-striped table-condensed"> |
||||
|
<thead> |
||||
|
{% if formset.readonly and not formset.queryset.exists %} |
||||
|
{% else %} |
||||
|
<tr> |
||||
|
{% for field in formset.forms.0 %} |
||||
|
{% if field.label and not field.is_hidden %} |
||||
|
<th for="{{ field.auto_id }}" class="control-label {% if field.field.required and not field|is_checkbox %}requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required and not field|is_checkbox %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</th> |
||||
|
{% endif %} |
||||
|
{% endfor %} |
||||
|
</tr> |
||||
|
{% endif %} |
||||
|
</thead> |
||||
|
|
||||
|
<tbody> |
||||
|
<tr class="hidden empty-form"> |
||||
|
{% for field in formset.empty_form %} |
||||
|
{% include 'bootstrap/field.html' with tag="td" form_show_labels=False %} |
||||
|
{% endfor %} |
||||
|
</tr> |
||||
|
|
||||
|
{% for form in formset %} |
||||
|
{% if form_show_errors and not form.is_extra %} |
||||
|
{% include "bootstrap/errors.html" %} |
||||
|
{% endif %} |
||||
|
|
||||
|
<tr> |
||||
|
{% for field in form %} |
||||
|
{% include 'bootstrap/field.html' with tag="td" form_show_labels=False %} |
||||
|
{% endfor %} |
||||
|
</tr> |
||||
|
{% endfor %} |
||||
|
</tbody> |
||||
|
</table> |
||||
|
|
||||
|
{% if inputs %} |
||||
|
<div class="form-actions"> |
||||
|
{% for input in inputs %} |
||||
|
{% include "bootstrap/layout/baseinput.html" %} |
||||
|
{% endfor %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
{% if formset_tag %}</form>{% endif %} |
||||
|
{% endspecialspaceless %} |
@ -0,0 +1,11 @@ |
|||||
|
{% load crispy_forms_utils %} |
||||
|
|
||||
|
{% specialspaceless %} |
||||
|
{% if include_media %}{{ form.media }}{% endif %} |
||||
|
{% if form_show_errors %} |
||||
|
{% include "bootstrap/errors.html" %} |
||||
|
{% endif %} |
||||
|
{% for field in form %} |
||||
|
{% include field_template %} |
||||
|
{% endfor %} |
||||
|
{% endspecialspaceless %} |
@ -0,0 +1,8 @@ |
|||||
|
{% with formset.management_form as form %} |
||||
|
{% include 'bootstrap/uni_form.html' %} |
||||
|
{% endwith %} |
||||
|
{% for form in formset %} |
||||
|
<div class="multiField"> |
||||
|
{% include 'bootstrap/uni_form.html' %} |
||||
|
</div> |
||||
|
{% endfor %} |
@ -0,0 +1,19 @@ |
|||||
|
{% load crispy_forms_utils %} |
||||
|
|
||||
|
{% specialspaceless %} |
||||
|
{% if form_tag %}<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if form.is_multipart %} enctype="multipart/form-data"{% endif %}>{% endif %} |
||||
|
{% if form_method|lower == 'post' and not disable_csrf %} |
||||
|
{% csrf_token %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% include "bootstrap/display_form.html" %} |
||||
|
|
||||
|
{% if inputs %} |
||||
|
<div class="form-actions"> |
||||
|
{% for input in inputs %} |
||||
|
{% include "bootstrap/layout/baseinput.html" %} |
||||
|
{% endfor %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
{% if form_tag %}</form>{% endif %} |
||||
|
{% endspecialspaceless %} |
@ -0,0 +1,30 @@ |
|||||
|
{% load crispy_forms_tags %} |
||||
|
{% load crispy_forms_utils %} |
||||
|
|
||||
|
{% specialspaceless %} |
||||
|
{% if formset_tag %} |
||||
|
<form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}> |
||||
|
{% endif %} |
||||
|
{% if formset_method|lower == 'post' and not disable_csrf %} |
||||
|
{% csrf_token %} |
||||
|
{% endif %} |
||||
|
|
||||
|
<div> |
||||
|
{{ formset.management_form|crispy }} |
||||
|
</div> |
||||
|
|
||||
|
{% include "bootstrap/errors_formset.html" %} |
||||
|
|
||||
|
{% for form in formset %} |
||||
|
{% include "bootstrap/display_form.html" %} |
||||
|
{% endfor %} |
||||
|
|
||||
|
{% if inputs %} |
||||
|
<div class="form-actions"> |
||||
|
{% for input in inputs %} |
||||
|
{% include "bootstrap/layout/baseinput.html" %} |
||||
|
{% endfor %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
{% if formset_tag %}</form>{% endif %} |
||||
|
{% endspecialspaceless %} |
@ -0,0 +1,12 @@ |
|||||
|
<div class="panel panel-default"> |
||||
|
<div class="panel-heading"> |
||||
|
<h4 class="panel-title"> |
||||
|
<a class="accordion-toggle" data-toggle="collapse" data-parent="#{{ div.data_parent }}" href="#{{ div.css_id }}">{{ div.name }}</a> |
||||
|
</h4> |
||||
|
</div> |
||||
|
<div id="{{ div.css_id }}" class="panel-collapse collapse{% if div.active %} in{% endif %}" > |
||||
|
<div class="panel-body"> |
||||
|
{{ fields|safe }} |
||||
|
</div> |
||||
|
</div> |
||||
|
</div> |
@ -0,0 +1,3 @@ |
|||||
|
<div class="panel-group" id="{{ accordion.css_id }}"> |
||||
|
{{ content|safe }} |
||||
|
</div> |
@ -0,0 +1,22 @@ |
|||||
|
{% for fieldset in form.fieldsets %} |
||||
|
<fieldset class="fieldset-{{ forloop.counter }} {{ fieldset.classes }}"> |
||||
|
{% if fieldset.legend %} |
||||
|
<legend>{{ fieldset.legend }}</legend> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if fieldset.description %} |
||||
|
<p class="description">{{ fieldset.description }}</p> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% for field in fieldset %} |
||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
{% include "bootstrap3/field.html" %} |
||||
|
{% endif %} |
||||
|
{% endfor %} |
||||
|
{% if not forloop.last or not fieldset_open %} |
||||
|
</fieldset> |
||||
|
{% endif %} |
||||
|
{% endfor %} |
||||
|
|
@ -0,0 +1,9 @@ |
|||||
|
{% if form.form_html %} |
||||
|
{% if include_media %}{{ form.media }}{% endif %} |
||||
|
{% if form_show_errors %} |
||||
|
{% include "bootstrap3/errors.html" %} |
||||
|
{% endif %} |
||||
|
{{ form.form_html }} |
||||
|
{% else %} |
||||
|
{% include "bootstrap3/uni_form.html" %} |
||||
|
{% endif %} |
@ -0,0 +1,8 @@ |
|||||
|
{% if form.non_field_errors %} |
||||
|
<div class="alert alert-block alert-danger"> |
||||
|
{% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %} |
||||
|
<ul> |
||||
|
{{ form.non_field_errors|unordered_list }} |
||||
|
</ul> |
||||
|
</div> |
||||
|
{% endif %} |
@ -0,0 +1,9 @@ |
|||||
|
{% if formset.non_form_errors %} |
||||
|
<div class="alert alert-block alert-danger"> |
||||
|
{% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %} |
||||
|
<ul> |
||||
|
{{ formset.non_form_errors|unordered_list }} |
||||
|
</ul> |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
|
@ -0,0 +1,52 @@ |
|||||
|
{% load crispy_forms_field %} |
||||
|
|
||||
|
{% if field.is_hidden %} |
||||
|
{{ field }} |
||||
|
{% else %} |
||||
|
{% if field|is_checkbox %} |
||||
|
<div class="form-group"> |
||||
|
{% if label_class %} |
||||
|
<div class="controls {% for offset in bootstrap_checkbox_offsets %}{{ offset }} {% endfor %}{{ field_class }}"> |
||||
|
{% endif %} |
||||
|
{% endif %} |
||||
|
<{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" {% if not field|is_checkbox %}class="form-group{% else %}class="checkbox{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} has-error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> |
||||
|
{% if field.label and not field|is_checkbox and form_show_labels %} |
||||
|
<label for="{{ field.id_for_label }}" class="control-label {{ label_class }}{% if field.field.required %} requiredField{% endif %}"> |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field|is_checkboxselectmultiple %} |
||||
|
{% include 'bootstrap3/layout/checkboxselectmultiple.html' %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if field|is_radioselect %} |
||||
|
{% include 'bootstrap3/layout/radioselect.html' %} |
||||
|
{% endif %} |
||||
|
|
||||
|
{% if not field|is_checkboxselectmultiple and not field|is_radioselect %} |
||||
|
{% if field|is_checkbox and form_show_labels %} |
||||
|
<label for="{{ field.id_for_label }}" class="{% if field.field.required %} requiredField{% endif %}"> |
||||
|
{% crispy_field field %} |
||||
|
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} |
||||
|
</label> |
||||
|
{% include 'bootstrap3/layout/help_text_and_errors.html' %} |
||||
|
{% else %} |
||||
|
<div class="controls {{ field_class }}"> |
||||
|
{% if field|is_multivalue %} |
||||
|
{% crispy_field field %} |
||||
|
{% else %} |
||||
|
{% crispy_field field 'class' 'form-control' %} |
||||
|
{% endif %} |
||||
|
{% include 'bootstrap3/layout/help_text_and_errors.html' %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
{% endif %} |
||||
|
</{% if tag %}{{ tag }}{% else %}div{% endif %}> |
||||
|
{% if field|is_checkbox %} |
||||
|
{% if label_class %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
</div> |
||||
|
{% endif %} |
||||
|
{% endif %} |
@ -0,0 +1,13 @@ |
|||||
|
{% if inputs %} |
||||
|
<div class="form-group"> |
||||
|
{% if label_class %} |
||||
|
<div class="aab controls {{ label_class }}"></div> |
||||
|
{% endif %} |
||||
|
|
||||
|
<div class="controls {{ field_class }}"> |
||||
|
{% for input in inputs %} |
||||
|
{% include "bootstrap3/layout/baseinput.html" %} |
||||
|
{% endfor %} |
||||
|
</div> |
||||
|
</div> |
||||
|
{% endif %} |
@ -0,0 +1,4 @@ |
|||||
|
<div{% if alert.css_id %} id="{{ alert.css_id }}"{% endif %}{% if alert.css_class %} class="{{ alert.css_class }}"{% endif %}> |
||||
|
{% if dismiss %}<button type="button" class="close" data-dismiss="alert">×</button>{% endif %} |
||||
|
{{ content|safe }} |
||||
|
</div> |
@ -0,0 +1,9 @@ |
|||||
|
<input type="{{ input.input_type }}" |
||||
|
name="{% if input.name|wordcount > 1 %}{{ input.name|slugify }}{% else %}{{ input.name }}{% endif %}" |
||||
|
value="{{ input.value }}" |
||||
|
{% if input.input_type != "hidden" %} |
||||
|
class="{{ input.field_classes }}" |
||||
|
id="{% if input.id %}{{ input.id }}{% else %}{{ input.input_type }}-id-{{ input.name|slugify }}{% endif %}" |
||||
|
{% endif %} |
||||
|
{{ input.flat_attrs|safe }} |
||||
|
/> |
@ -0,0 +1 @@ |
|||||
|
<button {{ button.flat_attrs|safe }}>{{ button.content|safe }}</button> |
@ -0,0 +1,4 @@ |
|||||
|
<div {% if buttonholder.css_id %}id="{{ buttonholder.css_id }}"{% endif %} |
||||
|
class="buttonHolder{% if buttonholder.css_class %} {{ buttonholder.css_class }}{% endif %}"> |
||||
|
{{ fields_output|safe }} |
||||
|
</div> |
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue