login page

This commit is contained in:
Alicja Cięciwa
2020-10-27 12:57:58 +01:00
commit cb8886666c
8545 changed files with 1082463 additions and 0 deletions

11
.idea/firma-system.iml generated Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (firma-system)" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/firma-system.iml" filepath="$PROJECT_DIR$/.idea/firma-system.iml" />
</modules>
</component>
</project>

7
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/Firma-system" vcs="Git" />
</component>
</project>

60
.idea/workspace.xml generated Normal file
View File

@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="15f590a5-5017-44f1-a85e-17dfe3fc5379" name="Default Changelist" comment="" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProjectId" id="1j71bSwhqpUMSNPYaQQ9lvdeSR6" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="PropertiesComponent">
<property name="last_opened_file_path" value="$PROJECT_DIR$/accounts" />
</component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="C:\Users\Alicja\Dev\firma-system\accounts" />
</key>
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="15f590a5-5017-44f1-a85e-17dfe3fc5379" name="Default Changelist" comment="" />
<created>1603140386736</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1603140386736</updated>
</task>
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
</project>

View File

@@ -0,0 +1,980 @@
Django was originally created in late 2003 at World Online, the Web division
of the Lawrence Journal-World newspaper in Lawrence, Kansas.
Here is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS --
people who have submitted patches, reported bugs, added translations, helped
answer newbie questions, and generally made Django that much better:
Aaron Cannon <cannona@fireantproductions.com>
Aaron Swartz <http://www.aaronsw.com/>
Aaron T. Myers <atmyers@gmail.com>
Abeer Upadhyay <ab.esquarer@gmail.com>
Abhijeet Viswa <abhijeetviswa@gmail.com>
Abhinav Patil <https://github.com/ubadub/>
Abhishek Gautam <abhishekg1128@yahoo.com>
Adam Allred <adam.w.allred@gmail.com>
Adam Bogdał <adam@bogdal.pl>
Adam Donaghy
Adam Johnson <https://github.com/adamchainz>
Adam Malinowski <https://adammalinowski.co.uk/>
Adam Vandenberg
Adiyat Mubarak <adiyatmubarak@gmail.com>
Adnan Umer <u.adnan@outlook.com>
Adrian Holovaty <adrian@holovaty.com>
Adrien Lemaire <lemaire.adrien@gmail.com>
Afonso Fernández Nogueira <fonzzo.django@gmail.com>
AgarFu <heaven@croasanaso.sytes.net>
Ahmad Alhashemi <trans@ahmadh.com>
Ahmad Al-Ibrahim
Ahmed Eltawela <https://github.com/ahmedabt>
ajs <adi@sieker.info>
Akash Agrawal <akashrocksha@gmail.com>
Akis Kesoglou <akiskesoglou@gmail.com>
Aksel Ethem <aksel.ethem@gmail.com>
Akshesh Doshi <aksheshdoshi+django@gmail.com>
alang@bright-green.com
Alasdair Nicol <https://al.sdair.co.uk/>
Albert Wang <https://github.com/albertyw/>
Alcides Fonseca
Aldian Fazrihady <mobile@aldian.net>
Aleksandra Sendecka <asendecka@hauru.eu>
Aleksi Häkli <aleksi.hakli@iki.fi>
Alexander Dutton <dev@alexdutton.co.uk>
Alexander Myodov <alex@myodov.com>
Alexandr Tatarinov <tatarinov1997@gmail.com>
Alex Aktsipetrov <alex.akts@gmail.com>
Alex Becker <https://alexcbecker.net/>
Alex Couper <http://alexcouper.com/>
Alex Dedul
Alex Gaynor <alex.gaynor@gmail.com>
Alex Hill <alex@hill.net.au>
Alex Ogier <alex.ogier@gmail.com>
Alex Robbins <alexander.j.robbins@gmail.com>
Alexey Boriskin <alex@boriskin.me>
Alexey Tsivunin <most-208@yandex.ru>
Aljosa Mohorovic <aljosa.mohorovic@gmail.com>
Amit Chakradeo <https://amit.chakradeo.net/>
Amit Ramon <amit.ramon@gmail.com>
Amit Upadhyay <http://www.amitu.com/blog/>
A. Murat Eren <meren@pardus.org.tr>
Ana Belen Sarabia <belensarabia@gmail.com>
Ana Krivokapic <https://github.com/infraredgirl>
Andi Albrecht <albrecht.andi@gmail.com>
André Ericson <de.ericson@gmail.com>
Andrei Kulakov <andrei.avk@gmail.com>
Andreas
Andreas Mock <andreas.mock@web.de>
Andreas Pelme <andreas@pelme.se>
Andrés Torres Marroquín <andres.torres.marroquin@gmail.com>
Andrew Brehaut <https://brehaut.net/blog>
Andrew Clark <amclark7@gmail.com>
Andrew Durdin <adurdin@gmail.com>
Andrew Godwin <andrew@aeracode.org>
Andrew Pinkham <http://AndrewsForge.com>
Andrews Medina <andrewsmedina@gmail.com>
Andriy Sokolovskiy <me@asokolovskiy.com>
Andy Dustman <farcepest@gmail.com>
Andy Gayton <andy-django@thecablelounge.com>
andy@jadedplanet.net
Anssi Kääriäinen <akaariai@gmail.com>
ant9000@netwise.it
Anthony Briggs <anthony.briggs@gmail.com>
Anton Samarchyan <desecho@gmail.com>
Antoni Aloy
Antonio Cavedoni <http://cavedoni.com/>
Antonis Christofides <anthony@itia.ntua.gr>
Antti Haapala <antti@industrialwebandmagic.com>
Antti Kaihola <http://djangopeople.net/akaihola/>
Anubhav Joshi <anubhav9042@gmail.com>
Aram Dulyan
arien <regexbot@gmail.com>
Armin Ronacher
Aron Podrigal <aronp@guaranteedplus.com>
Artem Gnilov <boobsd@gmail.com>
Arthur <avandorp@gmail.com>
Arthur Koziel <http://arthurkoziel.com>
Arthur Rio <arthur.rio44@gmail.com>
Arvis Bickovskis <viestards.lists@gmail.com>
Aryeh Leib Taurog <http://www.aryehleib.com/>
A S Alam <aalam@users.sf.net>
Asif Saif Uddin <auvipy@gmail.com>
atlithorn <atlithorn@gmail.com>
Audrey Roy <http://audreymroy.com/>
av0000@mail.ru
Axel Haustant <noirbizarre@gmail.com>
Aymeric Augustin <aymeric.augustin@m4x.org>
Bahadır Kandemir <bahadir@pardus.org.tr>
Baishampayan Ghose
Baptiste Mispelon <bmispelon@gmail.com>
Barry Pederson <bp@barryp.org>
Bartolome Sanchez Salado <i42sasab@uco.es>
Bartosz Grabski <bartosz.grabski@gmail.com>
Bashar Al-Abdulhadi
Bastian Kleineidam <calvin@debian.org>
Batiste Bieler <batiste.bieler@gmail.com>
Batman
Batuhan Taskaya <batuhanosmantaskaya@gmail.com>
Baurzhan Ismagulov <ibr@radix50.net>
Ben Dean Kawamura <ben.dean.kawamura@gmail.com>
Ben Firshman <ben@firshman.co.uk>
Ben Godfrey <http://aftnn.org>
Benjamin Wohlwend <piquadrat@gmail.com>
Ben Khoo <khoobks@westnet.com.au>
Ben Slavin <benjamin.slavin@gmail.com>
Ben Sturmfels <ben@sturm.com.au>
Berker Peksag <berker.peksag@gmail.com>
Bernd Schlapsi
Bernhard Essl <me@bernhardessl.com>
berto
Bill Fenner <fenner@gmail.com>
Bjørn Stabell <bjorn@exoweb.net>
Bo Marchman <bo.marchman@gmail.com>
Bogdan Mateescu
Bojan Mihelac <bmihelac@mihelac.org>
Bouke Haarsma <bouke@haarsma.eu>
Božidar Benko <bbenko@gmail.com>
Brad Melin <melinbrad@gmail.com>
Brandon Chinn <https://brandonchinn178.github.io/>
Brant Harris
Brendan Hayward <brendanhayward85@gmail.com>
Brendan Quinn <brendan@cluefulmedia.com>
Brenton Simpson <http://theillustratedlife.com>
Brett Cannon <brett@python.org>
Brett Hoerner <bretthoerner@bretthoerner.com>
Brian Beck <http://blog.brianbeck.com/>
Brian Fabian Crain <http://www.bfc.do/>
Brian Harring <ferringb@gmail.com>
Brian Helba <brian.helba@kitware.com>
Brian Ray <http://brianray.chipy.org/>
Brian Rosner <brosner@gmail.com>
Bruce Kroeze <https://coderseye.com/>
Bruno Alla <alla.brunoo@gmail.com>
Bruno Renié <buburno@gmail.com>
brut.alll@gmail.com
Bryan Chow <bryan at verdjn dot com>
Bryan Veloso <bryan@revyver.com>
bthomas
btoll@bestweb.net
C8E
Caio Ariede <caio.ariede@gmail.com>
Calvin Spealman <ironfroggy@gmail.com>
Cameron Curry
Cameron Knight (ckknight)
Can Burak Çilingir <canburak@cs.bilgi.edu.tr>
Can Sarıgöl <ertugrulsarigol@gmail.com>
Carl Meyer <carl@oddbird.net>
Carles Pina i Estany <carles@pina.cat>
Carlos Eduardo de Paula <carlosedp@gmail.com>
Carlos Matías de la Torre <cmdelatorre@gmail.com>
Carlton Gibson <carlton.gibson@noumenal.es>
cedric@terramater.net
Chad Whitman <chad.whitman@icloud.com>
ChaosKCW
Charlie Leifer <coleifer@gmail.com>
charly.wilhelm@gmail.com
Chason Chaffin <chason@gmail.com>
Cheng Zhang
Chris Adams
Chris Beaven <smileychris@gmail.com>
Chris Bennett <chrisrbennett@yahoo.com>
Chris Cahoon <chris.cahoon@gmail.com>
Chris Chamberlin <dja@cdc.msbx.net>
Chris Jerdonek
Chris Jones <chris@brack3t.com>
Chris Lamb <chris@chris-lamb.co.uk>
Chris Streeter <chris@chrisstreeter.com>
Christian Barcenas <christian@cbarcenas.com>
Christian Metts
Christian Oudard <christian.oudard@gmail.com>
Christian Tanzer <tanzer@swing.co.at>
Christoffer Sjöbergsson
Christophe Pettus <xof@thebuild.com>
Christopher Adams <http://christopheradams.info>
Christopher Babiak <chrisbabiak@gmail.com>
Christopher Lenz <https://www.cmlenz.net/>
Christoph Mędrela <chris.medrela@gmail.com>
Chris Wagner <cw264701@ohio.edu>
Chris Wesseling <Chris.Wesseling@cwi.nl>
Chris Wilson <chris+github@qwirx.com>
Claude Paroz <claude@2xlibre.net>
Clint Ecker
colin@owlfish.com
Colin Wood <cwood06@gmail.com>
Collin Anderson <cmawebsite@gmail.com>
Collin Grady <collin@collingrady.com>
Colton Hicks <coltonbhicks@gmail.com>
Craig Blaszczyk <masterjakul@gmail.com>
crankycoder@gmail.com
Curtis Maloney (FunkyBob) <curtis@tinbrain.net>
dackze+django@gmail.com
Dagur Páll Ammendrup <dagurp@gmail.com>
Dane Springmeyer
Dan Fairs <dan@fezconsulting.com>
Daniel Alves Barbosa de Oliveira Vaz <danielvaz@gmail.com>
Daniel Duan <DaNmarner@gmail.com>
Daniele Procida <daniele@vurt.org>
Daniel Greenfeld
dAniel hAhler
Daniel Jilg <daniel@breakthesystem.org>
Daniel Lindsley <daniel@toastdriven.com>
Daniel Poelzleithner <https://poelzi.org/>
Daniel Pyrathon <pirosb3@gmail.com>
Daniel Roseman <http://roseman.org.uk/>
Daniel Tao <https://philosopherdeveloper.com/>
Daniel Wiesmann <daniel.wiesmann@gmail.com>
Danilo Bargen
Dan Johnson <danj.py@gmail.com>
Dan Palmer <dan@danpalmer.me>
Dan Poirier <poirier@pobox.com>
Dan Stephenson <http://dan.io/>
Dan Watson <http://danwatson.net/>
dave@thebarproject.com
David Ascher <https://ascher.ca/>
David Avsajanishvili <avsd05@gmail.com>
David Blewett <david@dawninglight.net>
David Brenneman <http://davidbrenneman.com>
David Cramer <dcramer@gmail.com>
David Danier <david.danier@team23.de>
David Eklund
David Foster <david@dafoster.net>
David Gouldin <dgouldin@gmail.com>
david@kazserve.org
David Krauth
David Larlet <https://larlet.fr/david/>
David Reynolds <david@reynoldsfamily.org.uk>
David Sanders <dsanders11@ucsbalum.com>
David Schein
David Tulig <david.tulig@gmail.com>
David Wobrock <david.wobrock@gmail.com>
Davide Ceretti <dav.ceretti@gmail.com>
Deep L. Sukhwani <deepsukhwani@gmail.com>
Deepak Thukral <deep.thukral@gmail.com>
Denis Kuzmichyov <kuzmichyov@gmail.com>
Dennis Schwertel <dennisschwertel@gmail.com>
Derek Willis <http://blog.thescoop.org/>
Deric Crago <deric.crago@gmail.com>
deric@monowerks.com
Deryck Hodge <http://www.devurandom.org/>
Dimitris Glezos <dimitris@glezos.com>
Dirk Datzert <dummy@habmalnefrage.de>
Dirk Eschler <dirk.eschler@gmx.net>
Dmitri Fedortchenko <zeraien@gmail.com>
Dmitry Jemerov <intelliyole@gmail.com>
dne@mayonnaise.net
Dolan Antenucci <antenucci.d@gmail.com>
Donald Harvey <donald@donaldharvey.co.uk>
Donald Stufft <donald@stufft.io>
Don Spaulding <donspauldingii@gmail.com>
Doug Beck <doug@douglasbeck.com>
Doug Napoleone <doug@dougma.com>
dready <wil@mojipage.com>
dusk@woofle.net
Dustyn Gibson <miigotu@gmail.com>
Ed Morley <https://github.com/edmorley>
eibaan@gmail.com
elky <http://elky.me/>
Emmanuelle Delescolle <https://github.com/nanuxbe>
Emil Stenström <em@kth.se>
enlight
Enrico <rico.bl@gmail.com>
Eric Boersma <eric.boersma@gmail.com>
Eric Brandwein <brandweineric@gmail.com>
Eric Floehr <eric@intellovations.com>
Eric Florenzano <floguy@gmail.com>
Eric Holscher <http://ericholscher.com>
Eric Moritz <http://eric.themoritzfamily.com/>
Eric Palakovich Carr <carreric@gmail.com>
Erik Karulf <erik@karulf.com>
Erik Romijn <django@solidlinks.nl>
eriks@win.tue.nl
Erwin Junge <erwin@junge.nl>
Esdras Beleza <linux@esdrasbeleza.com>
Espen Grindhaug <http://grindhaug.org/>
Eugene Lazutkin <http://lazutkin.com/blog/>
Evan Grim <https://github.com/egrim>
Fabrice Aneche <akh@nobugware.com>
Farhaan Bukhsh <farhaan.bukhsh@gmail.com>
favo@exoweb.net
fdr <drfarina@gmail.com>
Federico Capoano <nemesis@ninux.org>
Felipe Lee <felipe.lee.garcia@gmail.com>
Filip Noetzel <http://filip.noetzel.co.uk/>
Filip Wasilewski <filip.wasilewski@gmail.com>
Finn Gruwier Larsen <finn@gruwier.dk>
Flávio Juvenal da Silva Junior <flavio@vinta.com.br>
flavio.curella@gmail.com
Florian Apolloner <florian@apolloner.eu>
Florian Moussous <florian.moussous@gmail.com>
Fran Hrženjak <fran.hrzenjak@gmail.com>
Francisco Albarran Cristobal <pahko.xd@gmail.com>
Francisco Couzo <franciscouzo@gmail.com>
François Freitag <mail@franek.fr>
Frank Tegtmeyer <fte@fte.to>
Frank Wierzbicki
Frank Wiles <frank@revsys.com>
František Malina <fmalina@gmail.com>
Fraser Nevett <mail@nevett.org>
Gabriel Grant <g@briel.ca>
Gabriel Hurley <gabriel@strikeawe.com>
gandalf@owca.info
Garry Lawrence
Garry Polley <garrympolley@gmail.com>
Garth Kidd <http://www.deadlybloodyserious.com/>
Gary Wilson <gary.wilson@gmail.com>
Gasper Koren
Gasper Zejn <zejn@kiberpipa.org>
Gavin Wahl <gavinwahl@gmail.com>
Ge Hanbin <xiaomiba0904@gmail.com>
geber@datacollect.com
Geert Vanderkelen
George Karpenkov <george@metaworld.ru>
George Song <george@damacy.net>
George Vilches <gav@thataddress.com>
Georg "Hugo" Bauer <gb@hugo.westfalen.de>
Georgi Stanojevski <glisha@gmail.com>
Gerardo Orozco <gerardo.orozco.mosqueda@gmail.com>
Gil Gonçalves <lursty@gmail.com>
Girish Kumar <girishkumarkh@gmail.com>
Gisle Aas <gisle@aas.no>
Glenn Maynard <glenn@zewt.org>
glin@seznam.cz
GomoX <gomo@datafull.com>
Gonzalo Saavedra <gonzalosaavedra@gmail.com>
Gopal Narayanan <gopastro@gmail.com>
Graham Carlyle <graham.carlyle@maplecroft.net>
Grant Jenks <contact@grantjenks.com>
Greg Chapple <gregchapple1@gmail.com>
Gregor Allensworth <greg.allensworth@gmail.com>
Gregor Müllegger <gregor@muellegger.de>
Grigory Fateyev <greg@dial.com.ru>
Grzegorz Ślusarek <grzegorz.slusarek@gmail.com>
Guilherme Mesquita Gondim <semente@taurinus.org>
Guillaume Pannatier <guillaume.pannatier@gmail.com>
Gustavo Picon
hambaloney
Hang Park <hangpark@kaist.ac.kr>
Hannes Ljungberg <hannes.ljungberg@gmail.com>
Hannes Struß <x@hannesstruss.de>
Hasan Ramezani <hasan.r67@gmail.com>
Hawkeye
Helen Sherwood-Taylor <helen@rrdlabs.co.uk>
Henrique Romano <onaiort@gmail.com>
Henry Dang <henrydangprg@gmail.com>
Hidde Bultsma
Himanshu Chauhan <hchauhan1404@outlook.com>
hipertracker@gmail.com
Hiroki Kiyohara <hirokiky@gmail.com>
Honza Král <honza.kral@gmail.com>
Horst Gutmann <zerok@zerokspot.com>
Hugo Osvaldo Barrera <hugo@barrera.io>
HyukJin Jang <wkdgurwls00@naver.com>
Hyun Mi Ae
Iacopo Spalletti <i.spalletti@nephila.it>
Ian A Wilson <http://ianawilson.com>
Ian Clelland <clelland@gmail.com>
Ian G. Kelly <ian.g.kelly@gmail.com>
Ian Holsman <http://feh.holsman.net/>
Ian Lee <IanLee1521@gmail.com>
Ibon <ibonso@gmail.com>
Idan Gazit <idan@gazit.me>
Idan Melamed
Ifedapo Olarewaju <ifedapoolarewaju@gmail.com>
Igor Kolar <ike@email.si>
Illia Volochii <illia.volochii@gmail.com>
Ilya Semenov <semenov@inetss.com>
Ingo Klöcker <djangoproject@ingo-kloecker.de>
I.S. van Oostveen <v.oostveen@idca.nl>
ivan.chelubeev@gmail.com
Ivan Sagalaev (Maniac) <http://www.softwaremaniacs.org/>
Jaap Roes <jaap.roes@gmail.com>
Jack Moffitt <https://metajack.im/>
Jacob Burch <jacobburch@gmail.com>
Jacob Green
Jacob Kaplan-Moss <jacob@jacobian.org>
Jakub Paczkowski <jakub@paczkowski.eu>
Jakub Wilk <jwilk@jwilk.net>
Jakub Wiśniowski <restless.being@gmail.com>
james_027@yahoo.com
James Aylett
James Bennett <james@b-list.org>
James Murty
James Tauber <jtauber@jtauber.com>
James Timmins <jameshtimmins@gmail.com>
James Turk <dev@jamesturk.net>
James Wheare <django@sparemint.com>
Jannis Leidel <jannis@leidel.info>
Janos Guljas
Jan Pazdziora
Jan Rademaker
Jarek Głowacki <jarekwg@gmail.com>
Jarek Zgoda <jarek.zgoda@gmail.com>
Jason Davies (Esaj) <https://www.jasondavies.com/>
Jason Huggins <http://www.jrandolph.com/blog/>
Jason McBrayer <http://www.carcosa.net/jason/>
jason.sidabras@gmail.com
Jason Yan <tailofthesun@gmail.com>
Javier Mansilla <javimansilla@gmail.com>
Jay Parlar <parlar@gmail.com>
Jay Welborn <jesse.welborn@gmail.com>
Jay Wineinger <jay.wineinger@gmail.com>
J. Clifford Dyer <jcd@sdf.lonestar.org>
jcrasta@gmail.com
jdetaeye
Jeff Anderson <jefferya@programmerq.net>
Jeff Balogh <jbalogh@mozilla.com>
Jeff Hui <jeffkhui@gmail.com>
Jeffrey Gelens <jeffrey@gelens.org>
Jeff Triplett <jeff.triplett@gmail.com>
Jeffrey Yancey <jeffrey.yancey@gmail.com>
Jens Diemer <django@htfx.de>
Jens Page
Jensen Cochran <jensen.cochran@gmail.com>
Jeong-Min Lee <falsetru@gmail.com>
Jérémie Blaser <blaserje@gmail.com>
Jeremy Bowman <https://github.com/jmbowman>
Jeremy Carbaugh <jcarbaugh@gmail.com>
Jeremy Dunck <jdunck@gmail.com>
Jeremy Lainé <jeremy.laine@m4x.org>
Jesse Young <adunar@gmail.com>
Jezeniel Zapanta <jezeniel.zapanta@gmail.com>
jhenry <jhenry@theonion.com>
Jim Dalton <jim.dalton@gmail.com>
Jimmy Song <jaejoon@gmail.com>
Jiri Barton
Joachim Jablon <ewjoachim@gmail.com>
Joao Oliveira <joaoxsouls@gmail.com>
Joao Pedro Silva <j.pedro004@gmail.com>
Joe Heck <http://www.rhonabwy.com/wp/>
Joel Bohman <mail@jbohman.com>
Joel Heenan <joelh-django@planetjoel.com>
Joel Watts <joel@joelwatts.com>
Joe Topjian <http://joe.terrarum.net/geek/code/python/django/>
Johan C. Stöver <johan@nilling.nl>
Johann Queuniet <johann.queuniet@adh.naellia.eu>
john@calixto.net
John D'Agostino <john.dagostino@gmail.com>
John D'Ambrosio <dambrosioj@gmail.com>
John Huddleston <huddlej@wwu.edu>
John Moses <moses.john.r@gmail.com>
John Paulett <john@paulett.org>
John Shaffer <jshaffer2112@gmail.com>
Jökull Sólberg Auðunsson <jokullsolberg@gmail.com>
Jon Dufresne <jon.dufresne@gmail.com>
Jonas Haag <jonas@lophus.org>
Jonatas C. D. <jonatas.cd@gmail.com>
Jonathan Buchanan <jonathan.buchanan@gmail.com>
Jonathan Daugherty (cygnus) <http://www.cprogrammer.org/>
Jonathan Feignberg <jdf@pobox.com>
Jonathan Slenders
Jordan Dimov <s3x3y1@gmail.com>
Jordi J. Tablada <jordi.joan@gmail.com>
Jorge Bastida <me@jorgebastida.com>
Jorge Gajon <gajon@gajon.org>
José Tomás Tocino García <josetomas.tocino@gmail.com>
Josef Rousek <josef.rousek@gmail.com>
Joseph Kocherhans <joseph@jkocherhans.com>
Josh Smeaton <josh.smeaton@gmail.com>
Joshua Cannon <joshdcannon@gmail.com>
Joshua Ginsberg <jag@flowtheory.net>
Jozko Skrablin <jozko.skrablin@gmail.com>
J. Pablo Fernandez <pupeno@pupeno.com>
jpellerin@gmail.com
Juan Catalano <catalanojuan@gmail.com>
Juan Manuel Caicedo <juan.manuel.caicedo@gmail.com>
Juan Pedro Fisanotti <fisadev@gmail.com>
Julia Elman
Julia Matsieva <julia.matsieva@gmail.com>
Julian Bez
Julien Phalip <jphalip@gmail.com>
Junyoung Choi <cupjoo@gmail.com>
junzhang.jn@gmail.com
Jure Cuhalev <gandalf@owca.info>
Justin Bronn <jbronn@gmail.com>
Justine Tunney <jtunney@gmail.com>
Justin Lilly <justinlilly@gmail.com>
Justin Michalicek <jmichalicek@gmail.com>
Justin Myles Holmes <justin@slashrootcafe.com>
Jyrki Pulliainen <jyrki.pulliainen@gmail.com>
Kadesarin Sanjek
Karderio <karderio@gmail.com>
Karen Tracey <kmtracey@gmail.com>
Karol Sikora <elektrrrus@gmail.com>
Katherine “Kati” Michel <kthrnmichel@gmail.com>
Kathryn Killebrew <kathryn.killebrew@gmail.com>
Katie Miller <katie@sub50.com>
Keith Bussell <kbussell@gmail.com>
Kenneth Love <kennethlove@gmail.com>
Kent Hauser <kent@khauser.net>
Kevin Grinberg <kevin@kevingrinberg.com>
Kevin Kubasik <kevin@kubasik.net>
Kevin McConnell <kevin.mcconnell@gmail.com>
Kieran Holland <http://www.kieranholland.com>
kilian <kilian.cavalotti@lip6.fr>
Kim Joon Hwan 김준환 <xncbf12@gmail.com>
Klaas van Schelven <klaas@vanschelven.com>
knox <christobzr@gmail.com>
konrad@gwu.edu
Kowito Charoenratchatabhan <kowito@felspar.com>
Krišjānis Vaiders <krisjanisvaiders@gmail.com>
krzysiek.pawlik@silvermedia.pl
Krzysztof Jurewicz <krzysztof.jurewicz@gmail.com>
Krzysztof Kulewski <kulewski@gmail.com>
kurtiss@meetro.com
Lakin Wecker <lakin@structuredabstraction.com>
Lars Yencken <lars.yencken@gmail.com>
Lau Bech Lauritzen
Laurent Luce <https://www.laurentluce.com/>
Laurent Rahuel <laurent.rahuel@gmail.com>
lcordier@point45.com
Leah Culver <leah.culver@gmail.com>
Leandra Finger <leandra.finger@gmail.com>
Lee Reilly <lee@leereilly.net>
Lee Sanghyuck <shlee322@elab.kr>
Leo "hylje" Honkanen <sealage@gmail.com>
Leo Shklovskii
Leo Soto <leo.soto@gmail.com>
lerouxb@gmail.com
Lex Berezhny <lex@damoti.com>
Liang Feng <hutuworm@gmail.com>
limodou
Lincoln Smith <lincoln.smith@anu.edu.au>
Liu Yijie <007gzs@gmail.com>
Loek van Gent <loek@barakken.nl>
Loïc Bistuer <loic.bistuer@sixmedia.com>
Lowe Thiderman <lowe.thiderman@gmail.com>
Luan Pablo <luanpab@gmail.com>
Lucas Connors <https://www.revolutiontech.ca/>
Luciano Ramalho
Ludvig Ericson <ludvig.ericson@gmail.com>
Luis C. Berrocal <luis.berrocal.1942@gmail.com>
Łukasz Langa <lukasz@langa.pl>
Łukasz Rekucki <lrekucki@gmail.com>
Luke Granger-Brown <django@lukegb.com>
Luke Plant <L.Plant.98@cantab.net>
Maciej Fijalkowski
Maciej Wiśniowski <pigletto@gmail.com>
Mads Jensen <https://github.com/atombrella>
Makoto Tsuyuki <mtsuyuki@gmail.com>
Malcolm Tredinnick
Manuel Saelices <msaelices@yaco.es>
Manuzhai
Marc Aymerich Gubern
Marc Egli <frog32@me.com>
Marcel Telka <marcel@telka.sk>
Marc Fargas <telenieko@telenieko.com>
Marc Garcia <marc.garcia@accopensys.com>
Marcin Wróbel
Marc Remolt <m.remolt@webmasters.de>
Marc Tamlyn <marc.tamlyn@gmail.com>
Marc-Aurèle Brothier <ma.brothier@gmail.com>
Marian Andre <django@andre.sk>
Marijn Vriens <marijn@metronomo.cl>
Mario Gonzalez <gonzalemario@gmail.com>
Mariusz Felisiak <felisiak.mariusz@gmail.com>
Mark Biggers <biggers@utsl.com>
Mark Gensler <mark.gensler@protonmail.com>
mark@junklight.com
Mark Lavin <markdlavin@gmail.com>
Mark Sandstrom <mark@deliciouslynerdy.com>
Markus Amalthea Magnuson <markus.magnuson@gmail.com>
Markus Holtermann <https://markusholtermann.eu>
Marten Kenbeek <marten.knbk+django@gmail.com>
Marti Raudsepp <marti@juffo.org>
martin.glueck@gmail.com
Martin Green
Martin Kosír <martin@martinkosir.net>
Martin Mahner <https://www.mahner.org/>
Martin Maney <http://www.chipy.org/Martin_Maney>
Martin von Gagern <gagern@google.com>
Mart Sõmermaa <http://mrts.pri.ee/>
Marty Alchin <gulopine@gamemusic.org>
Masashi Shibata <m.shibata1020@gmail.com>
masonsimon+django@gmail.com
Massimiliano Ravelli <massimiliano.ravelli@gmail.com>
Massimo Scamarcia <massimo.scamarcia@gmail.com>
Mathieu Agopian <mathieu.agopian@gmail.com>
Matías Bordese
Matt Boersma <matt@sprout.org>
Matt Croydon <http://www.postneo.com/>
Matt Deacalion Stevens <matt@dirtymonkey.co.uk>
Matt Dennenbaum
Matthew Flanagan <https://wadofstuff.blogspot.com/>
Matthew Schinckel <matt@schinckel.net>
Matthew Somerville <matthew-django@dracos.co.uk>
Matthew Tretter <m@tthewwithanm.com>
Matthew Wilkes <matt@matthewwilkes.name>
Matthias Kestenholz <mk@406.ch>
Matthias Pronk <django@masida.nl>
Matt Hoskins <skaffenuk@googlemail.com>
Matt McClanahan <https://mmcc.cx/>
Matt Riggott
Matt Robenolt <m@robenolt.com>
Mattia Larentis <mattia@laretis.eu>
Mattia Procopio <promat85@gmail.com>
Mattias Loverot <mattias@stubin.se>
mattycakes@gmail.com
Max Burstein <http://maxburstein.com>
Max Derkachev <mderk@yandex.ru>
Maxime Lorant <maxime.lorant@gmail.com>
Maxime Turcotte <maxocub@riseup.net>
Maximilian Merz <django@mxmerz.de>
Maximillian Dornseif <md@hudora.de>
mccutchen@gmail.com
Meir Kriheli <http://mksoft.co.il/>
Michael S. Brown <michael@msbrown.net>
Michael Hall <mhall1@ualberta.ca>
Michael Josephson <http://www.sdjournal.com/>
Michael Manfre <mmanfre@gmail.com>
michael.mcewan@gmail.com
Michael Placentra II <someone@michaelplacentra2.net>
Michael Radziej <mir@noris.de>
Michael Sanders <m.r.sanders@gmail.com>
Michael Schwarz <michi.schwarz@gmail.com>
Michael Sinov <sihaelov@gmail.com>
Michael Thornhill <michael.thornhill@gmail.com>
Michal Chruszcz <troll@pld-linux.org>
michal@plovarna.cz
Michał Modzelewski <michal.modzelewski@gmail.com>
Mihai Damian <yang_damian@yahoo.com>
Mihai Preda <mihai_preda@yahoo.com>
Mikaël Barbero <mikael.barbero nospam at nospam free.fr>
Mike Axiak <axiak@mit.edu>
Mike Grouchy <https://mikegrouchy.com/>
Mike Malone <mjmalone@gmail.com>
Mike Richardson
Mike Wiacek <mjwiacek@google.com>
Mikhail Korobov <kmike84@googlemail.com>
Mikko Hellsing <mikko@sorl.net>
Mikołaj Siedlarek <mikolaj.siedlarek@gmail.com>
milkomeda
Milton Waddams
mitakummaa@gmail.com
mmarshall
Moayad Mardini <moayad.m@gmail.com>
Morgan Aubert <morgan.aubert@zoho.com>
Moritz Sichert <moritz.sichert@googlemail.com>
Morten Bagai <m@bagai.com>
msaelices <msaelices@gmail.com>
msundstr
Mushtaq Ali <mushtaak@gmail.com>
Mykola Zamkovoi <nickzam@gmail.com>
Nadège Michel <michel.nadege@gmail.com>
Nagy Károly <charlie@rendszergazda.com>
Nasimul Haque <nasim.haque@gmail.com>
Nasir Hussain <nasirhjafri@gmail.com>
Natalia Bidart <nataliabidart@gmail.com>
Nate Bragg <jonathan.bragg@alum.rpi.edu>
Nathan Gaberel <nathan@gnab.fr>
Neal Norwitz <nnorwitz@google.com>
Nebojša Dorđević
Ned Batchelder <https://nedbatchelder.com/>
Nena Kojadin <nena@kiberpipa.org>
Niall Dalton <niall.dalton12@gmail.com>
Niall Kelly <duke.sam.vimes@gmail.com>
Nick Efford <nick@efford.org>
Nick Lane <nick.lane.au@gmail.com>
Nick Pope <nick@nickpope.me.uk>
Nick Presta <nick@nickpresta.ca>
Nick Sandford <nick.sandford@gmail.com>
Nick Sarbicki <nick.a.sarbicki@gmail.com>
Niclas Olofsson <n@niclasolofsson.se>
Nicola Larosa <nico@teknico.net>
Nicolas Lara <nicolaslara@gmail.com>
Nicolas Noé <nicolas@niconoe.eu>
Niran Babalola <niran@niran.org>
Nis Jørgensen <nis@superlativ.dk>
Nowell Strite <https://nowell.strite.org/>
Nuno Mariz <nmariz@gmail.com>
oggie rob <oz.robharvey@gmail.com>
oggy <ognjen.maric@gmail.com>
Oliver Beattie <oliver@obeattie.com>
Oliver Rutherfurd <http://rutherfurd.net/>
Olivier Sels <olivier.sels@gmail.com>
Olivier Tabone <olivier.tabone@ripplemotion.fr>
Orestis Markou <orestis@orestis.gr>
Orne Brocaar <http://brocaar.com/>
Oscar Ramirez <tuxskar@gmail.com>
Ossama M. Khayat <okhayat@yahoo.com>
Owen Griffiths
Pablo Martín <goinnn@gmail.com>
Panos Laganakos <panos.laganakos@gmail.com>
Paolo Melchiorre <paolo@melchiorre.org>
Pascal Hartig <phartig@rdrei.net>
Pascal Varet
Patrik Sletmo <patrik.sletmo@gmail.com>
Paul Bissex <http://e-scribe.com/>
Paul Collier <paul@paul-collier.com>
Paul Collins <paul.collins.iii@gmail.com>
Paul Donohue <django@PaulSD.com>
Paul Lanier <planier@google.com>
Paul McLanahan <paul@mclanahan.net>
Paul McMillan <Paul@McMillan.ws>
Paulo Poiati <paulogpoiati@gmail.com>
Paulo Scardine <paulo@scardine.com.br>
Paul Smith <blinkylights23@gmail.com>
Pavel Kulikov <kulikovpavel@gmail.com>
pavithran s <pavithran.s@gmail.com>
Pavlo Kapyshin <i@93z.org>
permonik@mesias.brnonet.cz
Petar Marić <http://www.petarmaric.com/>
Pete Crosier <pete.crosier@gmail.com>
peter@mymart.com
Peter Sheats <sheats@gmail.com>
Peter van Kampen
Peter Zsoldos <http://zsoldosp.eu>
Pete Shinners <pete@shinners.org>
Petr Marhoun <petr.marhoun@gmail.com>
pgross@thoughtworks.com
phaedo <http://phaedo.cx/>
phil.h.smith@gmail.com
Philip Lindborg <philip.lindborg@gmail.com>
Philippe Raoult <philippe.raoult@n2nsoft.com>
phil@produxion.net
Piotr Jakimiak <piotr.jakimiak@gmail.com>
Piotr Lewandowski <piotr.lewandowski@gmail.com>
plisk
polpak@yahoo.com
pradeep.gowda@gmail.com
Preston Holmes <preston@ptone.com>
Preston Timmons <prestontimmons@gmail.com>
Priyansh Saxena <askpriyansh@gmail.com>
Przemysław Buczkowski <przemub@przemub.pl>
Przemysław Suliga <http://suligap.net>
Rachel Tobin <rmtobin@me.com>
Rachel Willmer <http://www.willmer.com/kb/>
Radek Švarz <https://www.svarz.cz/translate/>
Raffaele Salmaso <raffaele@salmaso.org>
Rajesh Dhawan <rajesh.dhawan@gmail.com>
Ramez Ashraf <ramezashraf@gmail.com>
Ramin Farajpour Cami <ramin.blackhat@gmail.com>
Ramiro Morales <ramiro@rmorales.net>
Ramon Saraiva <ramonsaraiva@gmail.com>
Ram Rachum <ram@rachum.com>
Randy Barlow <randy@electronsweatshop.com>
Raphaël Barrois <raphael.barrois@m4x.org>
Raphael Michel <mail@raphaelmichel.de>
Raúl Cumplido <raulcumplido@gmail.com>
Rebecca Smith <rebkwok@gmail.com>
Remco Wendt <remco.wendt@gmail.com>
Renaud Parent <renaud.parent@gmail.com>
Renbi Yu <averybigant@gmail.com>
Reza Mohammadi <reza@zeerak.ir>
rhettg@gmail.com
Ricardo Javier Cárdenes Medina <ricardo.cardenes@gmail.com>
ricardojbarrios@gmail.com
Riccardo Di Virgilio
Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>
Richard Davies <richard.davies@elastichosts.com>
Richard House <Richard.House@i-logue.com>
Rick Wagner <rwagner@physics.ucsd.edu>
Rigel Di Scala <rigel.discala@propylon.com>
Robert Coup
Robert Myers <myer0052@gmail.com>
Roberto Aguilar <roberto@baremetal.io>
Robert Rock Howard <http://djangomojo.com/>
Robert Wittams
Rob Golding-Day <rob@golding-day.com>
Rob Hudson <https://rob.cogit8.org/>
Rob Nguyen <tienrobertnguyenn@gmail.com>
Robin Munn <http://www.geekforgod.com/>
Rodrigo Pinheiro Marques de Araújo <fenrrir@gmail.com>
Romain Garrigues <romain.garrigues.cs@gmail.com>
Ronny Haryanto <https://ronny.haryan.to/>
Ross Poulton <ross@rossp.org>
Rozza <ross.lawley@gmail.com>
Rudolph Froger <rfroger@estrate.nl>
Rudy Mutter
Rune Rønde Laursen <runerl@skjoldhoej.dk>
Russell Cloran <russell@rucus.net>
Russell Keith-Magee <russell@keith-magee.com>
Russ Webber
Ryan Hall <ryanhall989@gmail.com>
ryankanno
Ryan Kelly <ryan@rfk.id.au>
Ryan Niemeyer <https://profiles.google.com/ryan.niemeyer/about>
Ryan Petrello <ryan@ryanpetrello.com>
Ryan Rubin <ryanmrubin@gmail.com>
Ryno Mathee <rmathee@gmail.com>
Sachin Jat <sanch.jat@gmail.com>
Sage M. Abdullah <https://github.com/laymonage>
Sam Newman <http://www.magpiebrain.com/>
Sander Dijkhuis <sander.dijkhuis@gmail.com>
Sanket Saurav <sanketsaurav@gmail.com>
Sanyam Khurana <sanyam.khurana01@gmail.com>
Sarthak Mehrish <sarthakmeh03@gmail.com>
schwank@gmail.com
Scot Hacker <shacker@birdhouse.org>
Scott Barr <scott@divisionbyzero.com.au>
Scott Fitsimones <scott@airgara.ge>
Scott Pashley <github@scottpashley.co.uk>
scott@staplefish.com
Sean Brant
Sebastian Hillig <sebastian.hillig@gmail.com>
Sebastian Spiegel <https://www.tivix.com/>
Segyo Myung <myungsekyo@gmail.com>
Selwin Ong <selwin@ui.co.id>
Sengtha Chay <sengtha@e-khmer.com>
Senko Rašić <senko.rasic@dobarkod.hr>
serbaut@gmail.com
Sergei Maertens <sergeimaertens@gmail.com>
Sergey Fedoseev <fedoseev.sergey@gmail.com>
Sergey Kolosov <m17.admin@gmail.com>
Seth Hill <sethrh@gmail.com>
Shai Berger <shai@platonix.com>
Shannon -jj Behrens <https://www.jjinux.com/>
Shawn Milochik <shawn@milochik.com>
Silvan Spross <silvan.spross@gmail.com>
Simeon Visser <http://simeonvisser.com>
Simon Blanchard
Simon Charette <charette.s@gmail.com>
Simon Greenhill <dev@simon.net.nz>
Simon Litchfield <simon@quo.com.au>
Simon Meers <simon@simonmeers.com>
Simon Williams
Simon Willison <simon@simonwillison.net>
Sjoerd Job Postmus
Slawek Mikula <slawek dot mikula at gmail dot com>
sloonz <simon.lipp@insa-lyon.fr>
smurf@smurf.noris.de
sopel
Srinivas Reddy Thatiparthy <thatiparthysreenivas@gmail.com>
Stanislas Guerra <stan@slashdev.me>
Stanislaus Madueke
Stanislav Karpov <work@stkrp.ru>
starrynight <cmorgh@gmail.com>
Stefan R. Filipek
Stefane Fermgier <sf@fermigier.com>
Stefano Rivera <stefano@rivera.za.net>
Stéphane Raimbault <stephane.raimbault@gmail.com>
Stephan Jaekel <steph@rdev.info>
Stephen Burrows <stephen.r.burrows@gmail.com>
Steven L. Smith (fvox13) <steven@stevenlsmith.com>
Steven Noorbergen (Xaroth) <xaroth+django@xaroth.nl>
Stuart Langridge <https://www.kryogenix.org/>
Subhav Gautam <subhavgautam@yahoo.co.uk>
Sujay S Kumar <sujay.skumar141295@gmail.com>
Sune Kirkeby <https://ibofobi.dk/>
Sung-Jin Hong <serialx.net@gmail.com>
SuperJared
Susan Tan <susan.tan.fleckerl@gmail.com>
Sutrisno Efendi <kangfend@gmail.com>
Swaroop C H <http://www.swaroopch.info>
Szilveszter Farkas <szilveszter.farkas@gmail.com>
Taavi Teska <taaviteska@gmail.com>
Tai Lee <real.human@mrmachine.net>
Takashi Matsuo <matsuo.takashi@gmail.com>
Tareque Hossain <http://www.codexn.com>
Taylor Mitchell <taylor.mitchell@gmail.com>
Terry Huang <terryh.tp@gmail.com>
thebjorn <bp@datakortet.no>
Thejaswi Puthraya <thejaswi.puthraya@gmail.com>
Thijs van Dien <thijs@vandien.net>
Thom Wiggers
Thomas Chaumeny <t.chaumeny@gmail.com>
Thomas Güttler <hv@tbz-pariv.de>
Thomas Kerpe <thomas@kerpe.net>
Thomas Sorrel
Thomas Steinacher <http://www.eggdrop.ch/>
Thomas Stromberg <tstromberg@google.com>
Thomas Tanner <tanner@gmx.net>
tibimicu@gmx.net
Tim Allen <tim@pyphilly.org>
Tim Givois <tim.givois.mendez@gmail.com>
Tim Graham <timograham@gmail.com>
Tim Heap <tim@timheap.me>
Tim Saylor <tim.saylor@gmail.com>
Tobias Kunze <rixx@cutebit.de>
Tobias McNulty <https://www.caktusgroup.com/blog/>
tobias@neuyork.de
Todd O'Bryan <toddobryan@mac.com>
Tom Carrick <https://www.carrick.eu>
Tom Christie <tom@tomchristie.com>
Tom Forbes <tom@tomforb.es>
Tom Insam
Tom Tobin
Tomáš Ehrlich <tomas.ehrlich@gmail.com>
Tomáš Kopeček <permonik@m6.cz>
Tome Cvitan <tome@cvitan.com>
Tomek Paczkowski <tomek@hauru.eu>
Tomer Chachamu
Tommy Beadle <tbeadle@gmail.com>
Tore Lundqvist <tore.lundqvist@gmail.com>
torne-django@wolfpuppy.org.uk
Travis Cline <travis.cline@gmail.com>
Travis Pinney
Travis Swicegood <travis@domain51.com>
Travis Terry <tdterry7@gmail.com>
Trevor Caira <trevor@caira.com>
Trey Long <trey@ktrl.com>
tstromberg@google.com
tt@gurgle.no
Tyler Tarabula <tyler.tarabula@gmail.com>
Tyson Clugg <tyson@clugg.net>
Tyson Tate <tyson@fallingbullets.com>
Unai Zalakain <unai@gisa-elkartea.org>
Valentina Mukhamedzhanova <umirra@gmail.com>
valtron
Vasiliy Stavenko <stavenko@gmail.com>
Vasil Vangelovski
Vibhu Agarwal <vibhu-agarwal.github.io>
Victor Andrée
viestards.lists@gmail.com
Viktor Danyliuk <v.v.danyliuk@gmail.com>
Ville Säävuori <https://www.unessa.net/>
Vinay Karanam <https://github.com/vinayinvicible>
Vinay Sajip <vinay_sajip@yahoo.co.uk>
Vincent Foley <vfoleybourgon@yahoo.ca>
Vinny Do <vdo.code@gmail.com>
Vitaly Babiy <vbabiy86@gmail.com>
Vladimir Kuzma <vladimirkuzma.ch@gmail.com>
Vlado <vlado@labath.org>
Vsevolod Solovyov
Vytis Banaitis <vytis.banaitis@gmail.com>
wam-djangobug@wamber.net
Wang Chun <wangchun@exoweb.net>
Warren Smith <warren@wandrsmith.net>
Waylan Limberg <waylan@gmail.com>
Wiktor Kołodziej <wiktor@pykonik.org>
Wiley Kestner <wiley.kestner@gmail.com>
Wiliam Alves de Souza <wiliamsouza83@gmail.com>
Will Ayd <william.ayd@icloud.com>
William Schwartz <wkschwartz@gmail.com>
Will Hardy <django@willhardy.com.au>
Wilson Miner <wminer@gmail.com>
Wim Glenn <hey@wimglenn.com>
wojtek
Xavier Francisco <xavier.n.francisco@gmail.com>
Xia Kai <https://blog.xiaket.org/>
Yann Fouillat <gagaro42@gmail.com>
Yann Malet
Yasushi Masuda <whosaysni@gmail.com>
ye7cakf02@sneakemail.com
ymasuda@ethercube.com
Yoong Kang Lim <yoongkang.lim@gmail.com>
Yusuke Miyazaki <miyazaki.dev@gmail.com>
Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>
Zachary Voase <zacharyvoase@gmail.com>
Zach Liu <zachliu@gmail.com>
Zach Thompson <zthompson47@gmail.com>
Zain Memon
Zak Johnson <zakj@nox.cx>
Žan Anderle <zan.anderle@gmail.com>
Zbigniew Siciarz <zbigniew@siciarz.net>
zegor
Zeynel Özdemir <ozdemir.zynl@gmail.com>
Zlatko Mašek <zlatko.masek@gmail.com>
zriv <https://github.com/zriv>
<Please alphabetize new entries>
A big THANK YOU goes to:
Rob Curley and Ralph Gage for letting us open-source Django.
Frank Wiles for making excellent arguments for open-sourcing, and for
his sage sysadmin advice.
Ian Bicking for convincing Adrian to ditch code generation.
Mark Pilgrim for "Dive Into Python" (https://www.diveinto.org/python3/).
Guido van Rossum for creating Python.

View File

@@ -0,0 +1 @@
pip

View File

@@ -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.

View File

@@ -0,0 +1,265 @@
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 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 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.

View File

@@ -0,0 +1,89 @@
Metadata-Version: 2.1
Name: Django
Version: 3.1.2
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.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
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.6
Requires-Dist: asgiref (~=3.2.10)
Requires-Dist: pytz
Requires-Dist: sqlparse (>=0.2.2)
Provides-Extra: argon2
Requires-Dist: argon2-cffi (>=16.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.freenode.net. Lots of helpful people hang
out there. See https://freenode.net/kb/answer/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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.33.1)
Root-Is-Purelib: true
Tag: py3-none-any

View File

@@ -0,0 +1,3 @@
[console_scripts]
django-admin = django.core.management:execute_from_command_line

View File

@@ -0,0 +1 @@
django

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,123 @@
import sys
import os
import re
import importlib
import warnings
is_pypy = '__pypy__' in sys.builtin_module_names
def warn_distutils_present():
if 'distutils' not in sys.modules:
return
if is_pypy and sys.version_info < (3, 7):
# PyPy for 3.6 unconditionally imports distutils, so bypass the warning
# https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
return
warnings.warn(
"Distutils was imported before Setuptools, but importing Setuptools "
"also replaces the `distutils` module in `sys.modules`. This may lead "
"to undesirable behaviors or errors. To avoid these issues, avoid "
"using distutils directly, ensure that setuptools is installed in the "
"traditional way (e.g. not an editable install), and/or make sure "
"that setuptools is always imported before distutils.")
def clear_distutils():
if 'distutils' not in sys.modules:
return
warnings.warn("Setuptools is replacing distutils.")
mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
for name in mods:
del sys.modules[name]
def enabled():
"""
Allow selection of distutils by environment variable.
"""
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')
return which == 'local'
def ensure_local_distutils():
clear_distutils()
distutils = importlib.import_module('setuptools._distutils')
distutils.__name__ = 'distutils'
sys.modules['distutils'] = distutils
# sanity check that submodules load as expected
core = importlib.import_module('distutils.core')
assert '_distutils' in core.__file__, core.__file__
def do_override():
"""
Ensure that the local copy of distutils is preferred over stdlib.
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
for more motivation.
"""
if enabled():
warn_distutils_present()
ensure_local_distutils()
class DistutilsMetaFinder:
def find_spec(self, fullname, path, target=None):
if path is not None:
return
method_name = 'spec_for_{fullname}'.format(**locals())
method = getattr(self, method_name, lambda: None)
return method()
def spec_for_distutils(self):
import importlib.abc
import importlib.util
class DistutilsLoader(importlib.abc.Loader):
def create_module(self, spec):
return importlib.import_module('setuptools._distutils')
def exec_module(self, module):
pass
return importlib.util.spec_from_loader('distutils', DistutilsLoader())
def spec_for_pip(self):
"""
Ensure stdlib distutils when running under pip.
See pypa/pip#8761 for rationale.
"""
if self.pip_imported_during_build():
return
clear_distutils()
self.spec_for_distutils = lambda: None
@staticmethod
def pip_imported_during_build():
"""
Detect if pip is being imported in a build script. Ref #2355.
"""
import traceback
return any(
frame.f_globals['__file__'].endswith('setup.py')
for frame, line in traceback.walk_stack(None)
)
DISTUTILS_FINDER = DistutilsMetaFinder()
def add_shim():
sys.meta_path.insert(0, DISTUTILS_FINDER)
def remove_shim():
try:
sys.meta_path.remove(DISTUTILS_FINDER)
except ValueError:
pass

View File

@@ -0,0 +1 @@
__import__('_distutils_hack').do_override()

View File

@@ -0,0 +1 @@
import _virtualenv

View File

@@ -0,0 +1,130 @@
"""Patches that are applied at runtime to the virtual environment"""
# -*- coding: utf-8 -*-
import os
import sys
VIRTUALENV_PATCH_FILE = os.path.join(__file__)
def patch_dist(dist):
"""
Distutils allows user to configure some arguments via a configuration file:
https://docs.python.org/3/install/index.html#distutils-configuration-files
Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up.
"""
# we cannot allow some install config as that would get packages installed outside of the virtual environment
old_parse_config_files = dist.Distribution.parse_config_files
def parse_config_files(self, *args, **kwargs):
result = old_parse_config_files(self, *args, **kwargs)
install = self.get_option_dict("install")
if "prefix" in install: # the prefix governs where to install the libraries
install["prefix"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix)
for base in ("purelib", "platlib", "headers", "scripts", "data"):
key = "install_{}".format(base)
if key in install: # do not allow global configs to hijack venv paths
install.pop(key, None)
return result
dist.Distribution.parse_config_files = parse_config_files
# Import hook that patches some modules to ignore configuration values that break package installation in case
# of virtual environments.
_DISTUTILS_PATCH = "distutils.dist", "setuptools.dist"
if sys.version_info > (3, 4):
# https://docs.python.org/3/library/importlib.html#setting-up-an-importer
from functools import partial
from importlib.abc import MetaPathFinder
from importlib.util import find_spec
class _Finder(MetaPathFinder):
"""A meta path finder that allows patching the imported distutils modules"""
fullname = None
# lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup,
# because there are gevent-based applications that need to be first to import threading by themselves.
# See https://github.com/pypa/virtualenv/issues/1895 for details.
lock = []
def find_spec(self, fullname, path, target=None):
if fullname in _DISTUTILS_PATCH and self.fullname is None:
# initialize lock[0] lazily
if len(self.lock) == 0:
import threading
lock = threading.Lock()
# there is possibility that two threads T1 and T2 are simultaneously running into find_spec,
# observing .lock as empty, and further going into hereby initialization. However due to the GIL,
# list.append() operation is atomic and this way only one of the threads will "win" to put the lock
# - that every thread will use - into .lock[0].
# https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
self.lock.append(lock)
with self.lock[0]:
self.fullname = fullname
try:
spec = find_spec(fullname, path)
if spec is not None:
# https://www.python.org/dev/peps/pep-0451/#how-loading-will-work
is_new_api = hasattr(spec.loader, "exec_module")
func_name = "exec_module" if is_new_api else "load_module"
old = getattr(spec.loader, func_name)
func = self.exec_module if is_new_api else self.load_module
if old is not func:
try:
setattr(spec.loader, func_name, partial(func, old))
except AttributeError:
pass # C-Extension loaders are r/o such as zipimporter with <python 3.7
return spec
finally:
self.fullname = None
@staticmethod
def exec_module(old, module):
old(module)
if module.__name__ in _DISTUTILS_PATCH:
patch_dist(module)
@staticmethod
def load_module(old, name):
module = old(name)
if module.__name__ in _DISTUTILS_PATCH:
patch_dist(module)
return module
sys.meta_path.insert(0, _Finder())
else:
# https://www.python.org/dev/peps/pep-0302/
from imp import find_module
from pkgutil import ImpImporter, ImpLoader
class _VirtualenvImporter(object, ImpImporter):
def __init__(self, path=None):
object.__init__(self)
ImpImporter.__init__(self, path)
def find_module(self, fullname, path=None):
if fullname in _DISTUTILS_PATCH:
try:
return _VirtualenvLoader(fullname, *find_module(fullname.split(".")[-1], path))
except ImportError:
pass
return None
class _VirtualenvLoader(object, ImpLoader):
def __init__(self, fullname, file, filename, etc):
object.__init__(self)
ImpLoader.__init__(self, fullname, file, filename, etc)
def load_module(self, fullname):
module = super(_VirtualenvLoader, self).load_module(fullname)
patch_dist(module)
module.__loader__ = None # distlib fallback
return module
sys.meta_path.append(_VirtualenvImporter())

View File

@@ -0,0 +1 @@
pip

View File

@@ -0,0 +1,23 @@
# This is the MIT license
Copyright (c) 2010 ActiveState Software Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,264 @@
Metadata-Version: 2.1
Name: appdirs
Version: 1.4.4
Summary: A small Python module for determining appropriate platform-specific dirs, e.g. a "user data dir".
Home-page: http://github.com/ActiveState/appdirs
Author: Trent Mick
Author-email: trentm@gmail.com
Maintainer: Jeff Rouse
Maintainer-email: jr@its.to
License: MIT
Keywords: application directory log cache user
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Software Development :: Libraries :: Python Modules
.. image:: https://secure.travis-ci.org/ActiveState/appdirs.png
:target: http://travis-ci.org/ActiveState/appdirs
the problem
===========
What directory should your app use for storing user data? If running on Mac OS X, you
should use::
~/Library/Application Support/<AppName>
If on Windows (at least English Win XP) that should be::
C:\Documents and Settings\<User>\Application Data\Local Settings\<AppAuthor>\<AppName>
or possibly::
C:\Documents and Settings\<User>\Application Data\<AppAuthor>\<AppName>
for `roaming profiles <http://bit.ly/9yl3b6>`_ but that is another story.
On Linux (and other Unices) the dir, according to the `XDG
spec <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>`_, is::
~/.local/share/<AppName>
``appdirs`` to the rescue
=========================
This kind of thing is what the ``appdirs`` module is for. ``appdirs`` will
help you choose an appropriate:
- user data dir (``user_data_dir``)
- user config dir (``user_config_dir``)
- user cache dir (``user_cache_dir``)
- site data dir (``site_data_dir``)
- site config dir (``site_config_dir``)
- user log dir (``user_log_dir``)
and also:
- is a single module so other Python packages can include their own private copy
- is slightly opinionated on the directory names used. Look for "OPINION" in
documentation and code for when an opinion is being applied.
some example output
===================
On Mac OS X::
>>> from appdirs import *
>>> appname = "SuperApp"
>>> appauthor = "Acme"
>>> user_data_dir(appname, appauthor)
'/Users/trentm/Library/Application Support/SuperApp'
>>> site_data_dir(appname, appauthor)
'/Library/Application Support/SuperApp'
>>> user_cache_dir(appname, appauthor)
'/Users/trentm/Library/Caches/SuperApp'
>>> user_log_dir(appname, appauthor)
'/Users/trentm/Library/Logs/SuperApp'
On Windows 7::
>>> from appdirs import *
>>> appname = "SuperApp"
>>> appauthor = "Acme"
>>> user_data_dir(appname, appauthor)
'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
>>> user_data_dir(appname, appauthor, roaming=True)
'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
>>> user_cache_dir(appname, appauthor)
'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
>>> user_log_dir(appname, appauthor)
'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
On Linux::
>>> from appdirs import *
>>> appname = "SuperApp"
>>> appauthor = "Acme"
>>> user_data_dir(appname, appauthor)
'/home/trentm/.local/share/SuperApp
>>> site_data_dir(appname, appauthor)
'/usr/local/share/SuperApp'
>>> site_data_dir(appname, appauthor, multipath=True)
'/usr/local/share/SuperApp:/usr/share/SuperApp'
>>> user_cache_dir(appname, appauthor)
'/home/trentm/.cache/SuperApp'
>>> user_log_dir(appname, appauthor)
'/home/trentm/.cache/SuperApp/log'
>>> user_config_dir(appname)
'/home/trentm/.config/SuperApp'
>>> site_config_dir(appname)
'/etc/xdg/SuperApp'
>>> os.environ['XDG_CONFIG_DIRS'] = '/etc:/usr/local/etc'
>>> site_config_dir(appname, multipath=True)
'/etc/SuperApp:/usr/local/etc/SuperApp'
``AppDirs`` for convenience
===========================
::
>>> from appdirs import AppDirs
>>> dirs = AppDirs("SuperApp", "Acme")
>>> dirs.user_data_dir
'/Users/trentm/Library/Application Support/SuperApp'
>>> dirs.site_data_dir
'/Library/Application Support/SuperApp'
>>> dirs.user_cache_dir
'/Users/trentm/Library/Caches/SuperApp'
>>> dirs.user_log_dir
'/Users/trentm/Library/Logs/SuperApp'
Per-version isolation
=====================
If you have multiple versions of your app in use that you want to be
able to run side-by-side, then you may want version-isolation for these
dirs::
>>> from appdirs import AppDirs
>>> dirs = AppDirs("SuperApp", "Acme", version="1.0")
>>> dirs.user_data_dir
'/Users/trentm/Library/Application Support/SuperApp/1.0'
>>> dirs.site_data_dir
'/Library/Application Support/SuperApp/1.0'
>>> dirs.user_cache_dir
'/Users/trentm/Library/Caches/SuperApp/1.0'
>>> dirs.user_log_dir
'/Users/trentm/Library/Logs/SuperApp/1.0'
appdirs Changelog
=================
appdirs 1.4.4
-------------
- [PR #92] Don't import appdirs from setup.py
Project officially classified as Stable which is important
for inclusion in other distros such as ActivePython.
First of several incremental releases to catch up on maintenance.
appdirs 1.4.3
-------------
- [PR #76] Python 3.6 invalid escape sequence deprecation fixes
- Fix for Python 3.6 support
appdirs 1.4.2
-------------
- [PR #84] Allow installing without setuptools
- [PR #86] Fix string delimiters in setup.py description
- Add Python 3.6 support
appdirs 1.4.1
-------------
- [issue #38] Fix _winreg import on Windows Py3
- [issue #55] Make appname optional
appdirs 1.4.0
-------------
- [PR #42] AppAuthor is now optional on Windows
- [issue 41] Support Jython on Windows, Mac, and Unix-like platforms. Windows
support requires `JNA <https://github.com/twall/jna>`_.
- [PR #44] Fix incorrect behaviour of the site_config_dir method
appdirs 1.3.0
-------------
- [Unix, issue 16] Conform to XDG standard, instead of breaking it for
everybody
- [Unix] Removes gratuitous case mangling of the case, since \*nix-es are
usually case sensitive, so mangling is not wise
- [Unix] Fixes the utterly wrong behaviour in ``site_data_dir``, return result
based on XDG_DATA_DIRS and make room for respecting the standard which
specifies XDG_DATA_DIRS is a multiple-value variable
- [Issue 6] Add ``*_config_dir`` which are distinct on nix-es, according to
XDG specs; on Windows and Mac return the corresponding ``*_data_dir``
appdirs 1.2.0
-------------
- [Unix] Put ``user_log_dir`` under the *cache* dir on Unix. Seems to be more
typical.
- [issue 9] Make ``unicode`` work on py3k.
appdirs 1.1.0
-------------
- [issue 4] Add ``AppDirs.user_log_dir``.
- [Unix, issue 2, issue 7] appdirs now conforms to `XDG base directory spec
<http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>`_.
- [Mac, issue 5] Fix ``site_data_dir()`` on Mac.
- [Mac] Drop use of 'Carbon' module in favour of hardcoded paths; supports
Python3 now.
- [Windows] Append "Cache" to ``user_cache_dir`` on Windows by default. Use
``opinion=False`` option to disable this.
- Add ``appdirs.AppDirs`` convenience class. Usage:
>>> dirs = AppDirs("SuperApp", "Acme", version="1.0")
>>> dirs.user_data_dir
'/Users/trentm/Library/Application Support/SuperApp/1.0'
- [Windows] Cherry-pick Komodo's change to downgrade paths to the Windows short
paths if there are high bit chars.
- [Linux] Change default ``user_cache_dir()`` on Linux to be singular, e.g.
"~/.superapp/cache".
- [Windows] Add ``roaming`` option to ``user_data_dir()`` (for use on Windows only)
and change the default ``user_data_dir`` behaviour to use a *non*-roaming
profile dir (``CSIDL_LOCAL_APPDATA`` instead of ``CSIDL_APPDATA``). Why? Because
a large roaming profile can cause login speed issues. The "only syncs on
logout" behaviour can cause surprises in appdata info.
appdirs 1.0.1 (never released)
------------------------------
Started this changelog 27 July 2010. Before that this module originated in the
`Komodo <http://www.activestate.com/komodo>`_ product as ``applib.py`` and then
as `applib/location.py
<http://github.com/ActiveState/applib/blob/master/applib/location.py>`_ (used by
`PyPM <http://code.activestate.com/pypm/>`_ in `ActivePython
<http://www.activestate.com/activepython>`_). This is basically a fork of
applib.py 1.0.1 and applib/location.py 1.0.1.

View File

@@ -0,0 +1,8 @@
__pycache__/appdirs.cpython-38.pyc,,
appdirs-1.4.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
appdirs-1.4.4.dist-info/LICENSE.txt,sha256=Nt200KdFqTqyAyA9cZCBSxuJcn0lTK_0jHp6-71HAAs,1097
appdirs-1.4.4.dist-info/METADATA,sha256=k5TVfXMNKGHTfp2wm6EJKTuGwGNuoQR5TqQgH8iwG8M,8981
appdirs-1.4.4.dist-info/RECORD,,
appdirs-1.4.4.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
appdirs-1.4.4.dist-info/top_level.txt,sha256=nKncE8CUqZERJ6VuQWL4_bkunSPDNfn7KZqb4Tr5YEM,8
appdirs.py,sha256=g99s2sXhnvTEm79oj4bWI0Toapc-_SmKKNXvOXHkVic,24720

View File

@@ -0,0 +1,6 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.34.2)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any

View File

@@ -0,0 +1 @@
appdirs

View File

@@ -0,0 +1,608 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2005-2010 ActiveState Software Inc.
# Copyright (c) 2013 Eddy Petrișor
"""Utilities for determining application-specific dirs.
See <http://github.com/ActiveState/appdirs> for details and usage.
"""
# Dev Notes:
# - MSDN on where to store app data files:
# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html
# - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
__version__ = "1.4.4"
__version_info__ = tuple(int(segment) for segment in __version__.split("."))
import sys
import os
PY3 = sys.version_info[0] == 3
if PY3:
unicode = str
if sys.platform.startswith('java'):
import platform
os_name = platform.java_ver()[3][0]
if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc.
system = 'win32'
elif os_name.startswith('Mac'): # "Mac OS X", etc.
system = 'darwin'
else: # "Linux", "SunOS", "FreeBSD", etc.
# Setting this to "linux2" is not ideal, but only Windows or Mac
# are actually checked for and the rest of the module expects
# *sys.platform* style strings.
system = 'linux2'
else:
system = sys.platform
def user_data_dir(appname=None, appauthor=None, version=None, roaming=False):
r"""Return full path to the user-specific data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user data directories are:
Mac OS X: ~/Library/Application Support/<AppName>
Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
That means, by default "~/.local/share/<AppName>".
"""
if system == "win32":
if appauthor is None:
appauthor = appname
const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
path = os.path.normpath(_get_win_folder(const))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
elif system == 'darwin':
path = os.path.expanduser('~/Library/Application Support/')
if appname:
path = os.path.join(path, appname)
else:
path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
r"""Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"multipath" is an optional parameter only applicable to *nix
which indicates that the entire list of data dirs should be
returned. By default, the first item from XDG_DATA_DIRS is
returned, or '/usr/local/share/<AppName>',
if XDG_DATA_DIRS is not set
Typical site data directories are:
Mac OS X: /Library/Application Support/<AppName>
Unix: /usr/local/share/<AppName> or /usr/share/<AppName>
Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName>
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7.
For Unix, this is using the $XDG_DATA_DIRS[0] default.
WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
"""
if system == "win32":
if appauthor is None:
appauthor = appname
path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
elif system == 'darwin':
path = os.path.expanduser('/Library/Application Support')
if appname:
path = os.path.join(path, appname)
else:
# XDG default for $XDG_DATA_DIRS
# only first, if multipath is False
path = os.getenv('XDG_DATA_DIRS',
os.pathsep.join(['/usr/local/share', '/usr/share']))
pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
if appname:
if version:
appname = os.path.join(appname, version)
pathlist = [os.sep.join([x, appname]) for x in pathlist]
if multipath:
path = os.pathsep.join(pathlist)
else:
path = pathlist[0]
return path
if appname and version:
path = os.path.join(path, version)
return path
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
r"""Return full path to the user-specific config dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user config directories are:
Mac OS X: same as user_data_dir
Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined
Win *: same as user_data_dir
For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
That means, by default "~/.config/<AppName>".
"""
if system in ["win32", "darwin"]:
path = user_data_dir(appname, appauthor, None, roaming)
else:
path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def site_config_dir(appname=None, appauthor=None, version=None, multipath=False):
r"""Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"multipath" is an optional parameter only applicable to *nix
which indicates that the entire list of config dirs should be
returned. By default, the first item from XDG_CONFIG_DIRS is
returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set
Typical site config directories are:
Mac OS X: same as site_data_dir
Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in
$XDG_CONFIG_DIRS
Win *: same as site_data_dir
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False
WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
"""
if system in ["win32", "darwin"]:
path = site_data_dir(appname, appauthor)
if appname and version:
path = os.path.join(path, version)
else:
# XDG default for $XDG_CONFIG_DIRS
# only first, if multipath is False
path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')
pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
if appname:
if version:
appname = os.path.join(appname, version)
pathlist = [os.sep.join([x, appname]) for x in pathlist]
if multipath:
path = os.pathsep.join(pathlist)
else:
path = pathlist[0]
return path
def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
r"""Return full path to the user-specific cache dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"opinion" (boolean) can be False to disable the appending of
"Cache" to the base app data dir for Windows. See
discussion below.
Typical user cache directories are:
Mac OS X: ~/Library/Caches/<AppName>
Unix: ~/.cache/<AppName> (XDG default)
Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache
On Windows the only suggestion in the MSDN docs is that local settings go in
the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming
app data dir (the default returned by `user_data_dir` above). Apps typically
put cache data somewhere *under* the given dir here. Some examples:
...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
...\Acme\SuperApp\Cache\1.0
OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
This can be disabled with the `opinion=False` option.
"""
if system == "win32":
if appauthor is None:
appauthor = appname
path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
if opinion:
path = os.path.join(path, "Cache")
elif system == 'darwin':
path = os.path.expanduser('~/Library/Caches')
if appname:
path = os.path.join(path, appname)
else:
path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def user_state_dir(appname=None, appauthor=None, version=None, roaming=False):
r"""Return full path to the user-specific state dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user state directories are:
Mac OS X: same as user_data_dir
Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined
Win *: same as user_data_dir
For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>
to extend the XDG spec and support $XDG_STATE_HOME.
That means, by default "~/.local/state/<AppName>".
"""
if system in ["win32", "darwin"]:
path = user_data_dir(appname, appauthor, None, roaming)
else:
path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def user_log_dir(appname=None, appauthor=None, version=None, opinion=True):
r"""Return full path to the user-specific log dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"opinion" (boolean) can be False to disable the appending of
"Logs" to the base app data dir for Windows, and "log" to the
base cache dir for Unix. See discussion below.
Typical user log directories are:
Mac OS X: ~/Library/Logs/<AppName>
Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined
Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs
On Windows the only suggestion in the MSDN docs is that local settings
go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
examples of what some windows apps use for a logs dir.)
OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
value for Windows and appends "log" to the user cache dir for Unix.
This can be disabled with the `opinion=False` option.
"""
if system == "darwin":
path = os.path.join(
os.path.expanduser('~/Library/Logs'),
appname)
elif system == "win32":
path = user_data_dir(appname, appauthor, version)
version = False
if opinion:
path = os.path.join(path, "Logs")
else:
path = user_cache_dir(appname, appauthor, version)
version = False
if opinion:
path = os.path.join(path, "log")
if appname and version:
path = os.path.join(path, version)
return path
class AppDirs(object):
"""Convenience wrapper for getting application dirs."""
def __init__(self, appname=None, appauthor=None, version=None,
roaming=False, multipath=False):
self.appname = appname
self.appauthor = appauthor
self.version = version
self.roaming = roaming
self.multipath = multipath
@property
def user_data_dir(self):
return user_data_dir(self.appname, self.appauthor,
version=self.version, roaming=self.roaming)
@property
def site_data_dir(self):
return site_data_dir(self.appname, self.appauthor,
version=self.version, multipath=self.multipath)
@property
def user_config_dir(self):
return user_config_dir(self.appname, self.appauthor,
version=self.version, roaming=self.roaming)
@property
def site_config_dir(self):
return site_config_dir(self.appname, self.appauthor,
version=self.version, multipath=self.multipath)
@property
def user_cache_dir(self):
return user_cache_dir(self.appname, self.appauthor,
version=self.version)
@property
def user_state_dir(self):
return user_state_dir(self.appname, self.appauthor,
version=self.version)
@property
def user_log_dir(self):
return user_log_dir(self.appname, self.appauthor,
version=self.version)
#---- internal support stuff
def _get_win_folder_from_registry(csidl_name):
"""This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
"""
if PY3:
import winreg as _winreg
else:
import _winreg
shell_folder_name = {
"CSIDL_APPDATA": "AppData",
"CSIDL_COMMON_APPDATA": "Common AppData",
"CSIDL_LOCAL_APPDATA": "Local AppData",
}[csidl_name]
key = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
dir, type = _winreg.QueryValueEx(key, shell_folder_name)
return dir
def _get_win_folder_with_pywin32(csidl_name):
from win32com.shell import shellcon, shell
dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)
# Try to make this a unicode path because SHGetFolderPath does
# not return unicode strings when there is unicode data in the
# path.
try:
dir = unicode(dir)
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in dir:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
try:
import win32api
dir = win32api.GetShortPathName(dir)
except ImportError:
pass
except UnicodeError:
pass
return dir
def _get_win_folder_with_ctypes(csidl_name):
import ctypes
csidl_const = {
"CSIDL_APPDATA": 26,
"CSIDL_COMMON_APPDATA": 35,
"CSIDL_LOCAL_APPDATA": 28,
}[csidl_name]
buf = ctypes.create_unicode_buffer(1024)
ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in buf:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
buf2 = ctypes.create_unicode_buffer(1024)
if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
buf = buf2
return buf.value
def _get_win_folder_with_jna(csidl_name):
import array
from com.sun import jna
from com.sun.jna.platform import win32
buf_size = win32.WinDef.MAX_PATH * 2
buf = array.zeros('c', buf_size)
shell = win32.Shell32.INSTANCE
shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
dir = jna.Native.toString(buf.tostring()).rstrip("\0")
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in dir:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
buf = array.zeros('c', buf_size)
kernel = win32.Kernel32.INSTANCE
if kernel.GetShortPathName(dir, buf, buf_size):
dir = jna.Native.toString(buf.tostring()).rstrip("\0")
return dir
if system == "win32":
try:
import win32com.shell
_get_win_folder = _get_win_folder_with_pywin32
except ImportError:
try:
from ctypes import windll
_get_win_folder = _get_win_folder_with_ctypes
except ImportError:
try:
import com.sun.jna
_get_win_folder = _get_win_folder_with_jna
except ImportError:
_get_win_folder = _get_win_folder_from_registry
#---- self test code
if __name__ == "__main__":
appname = "MyApp"
appauthor = "MyCompany"
props = ("user_data_dir",
"user_config_dir",
"user_cache_dir",
"user_state_dir",
"user_log_dir",
"site_data_dir",
"site_config_dir")
print("-- app dirs %s --" % __version__)
print("-- app dirs (with optional 'version')")
dirs = AppDirs(appname, appauthor, version="1.0")
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
print("\n-- app dirs (without optional 'version')")
dirs = AppDirs(appname, appauthor)
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
print("\n-- app dirs (without optional 'appauthor')")
dirs = AppDirs(appname)
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
print("\n-- app dirs (with disabled 'appauthor')")
dirs = AppDirs(appname, appauthor=False)
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))

View File

@@ -0,0 +1 @@
pip

View File

@@ -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.

View File

@@ -0,0 +1,229 @@
Metadata-Version: 2.1
Name: asgiref
Version: 3.2.10
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.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.5
Provides-Extra: tests
Requires-Dist: pytest ; extra == 'tests'
Requires-Dist: pytest-asyncio ; 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.
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.5 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
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 arbitary
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.
Cruicially, 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>`_.

View File

@@ -0,0 +1,24 @@
asgiref-3.2.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
asgiref-3.2.10.dist-info/LICENSE,sha256=uEZBXRtRTpwd_xSiLeuQbXlLxUbKYSn5UKGM0JHipmk,1552
asgiref-3.2.10.dist-info/METADATA,sha256=LzBbpVxLs55-21YTiQmIs3UJDo47oDfiN_rjHSpCKNc,8483
asgiref-3.2.10.dist-info/RECORD,,
asgiref-3.2.10.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92
asgiref-3.2.10.dist-info/top_level.txt,sha256=bokQjCzwwERhdBiPdvYEZa4cHxT4NCeAffQNUqJ8ssg,8
asgiref/__init__.py,sha256=b1ca8SRnNegOaCcqHfnPEedhi8qMtg3Vpu_VGcwqujs,23
asgiref/__pycache__/__init__.cpython-38.pyc,,
asgiref/__pycache__/compatibility.cpython-38.pyc,,
asgiref/__pycache__/current_thread_executor.cpython-38.pyc,,
asgiref/__pycache__/local.cpython-38.pyc,,
asgiref/__pycache__/server.cpython-38.pyc,,
asgiref/__pycache__/sync.cpython-38.pyc,,
asgiref/__pycache__/testing.cpython-38.pyc,,
asgiref/__pycache__/timeout.cpython-38.pyc,,
asgiref/__pycache__/wsgi.cpython-38.pyc,,
asgiref/compatibility.py,sha256=MVH2bEdiCMMVTLbE-1V6KiU7q4LwqzP7PIufeXa-njM,1598
asgiref/current_thread_executor.py,sha256=3dRFt3jAl_x1wr9prZZMut071pmdHdIwbTnUAYVejj4,2974
asgiref/local.py,sha256=7g_PSo5vqd-KRkO7SOgoktSWr85Etsi4rqJyF1VUXhw,4849
asgiref/server.py,sha256=iFJn_uD-poeHWgLOuSnKCVMS1HqqV-IOTOOC85fKr00,5915
asgiref/sync.py,sha256=NcVUMrm-5RC76g3cT2SsnRDgV5AArbZjO6Df3_j9alY,13376
asgiref/testing.py,sha256=3byNRV7Oto_Fg8Z-fErQJ3yGf7OQlcUexbN_cDQugzQ,3119
asgiref/timeout.py,sha256=Emw-Oop1pRfSc5YSMEYHgEz1802mP6JdA6bxH37bby8,3914
asgiref/wsgi.py,sha256=rxGUxQG4FsSJYXJekClLuAGM_rovnxfH1qrNt95CNaI,5606

View File

@@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.34.2)
Root-Is-Purelib: true
Tag: py3-none-any

View File

@@ -0,0 +1 @@
asgiref

View File

@@ -0,0 +1 @@
__version__ = "3.2.10"

View File

@@ -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

View File

@@ -0,0 +1,86 @@
import queue
import threading
import time
from concurrent.futures import Executor, Future
class _WorkItem(object):
"""
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"
)
# Keep getting work items and checking the future
try:
while True:
# Get a work item and run it
try:
work_item = self._work_queue.get(block=False)
except queue.Empty:
# See if the future is done (we only exit if the work queue is empty)
if future.done():
return
# Prevent hot-looping on nothing
time.sleep(0.001)
else:
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

View File

@@ -0,0 +1,122 @@
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.
"""
CLEANUP_INTERVAL = 60 # seconds
def __init__(self, thread_critical=False):
self._thread_critical = thread_critical
self._thread_lock = threading.RLock()
self._context_refs = weakref.WeakSet()
# Random suffixes stop accidental reuse between different Locals,
# though we try to force deletion as well.
self._attr_name = "_asgiref_local_impl_%s_%s" % (
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("%r object has no attribute %r" % (self, key))
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("%r object has no attribute %r" % (self, key))

View File

@@ -0,0 +1,154 @@
import asyncio
import logging
import time
import traceback
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 = self.application(scope=scope)
# Run it, and stash the future for later checking
future = asyncio.ensure_future(
application_instance(
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__)),
" {}".format(exception),
)

View File

@@ -0,0 +1,361 @@
import asyncio
import asyncio.coroutines
import functools
import os
import sys
import threading
from concurrent.futures import Future, ThreadPoolExecutor
from .current_thread_executor import CurrentThreadExecutor
from .local import Local
try:
import contextvars # Python 3.7+ only.
except ImportError:
contextvars = None
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))
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 = {}
# 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):
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_event_loop()
except RuntimeError:
# There's no event loop in this thread. Look for the threadlocal if
# we're inside SyncToAsync
self.main_event_loop = getattr(
SyncToAsync.threadlocal, "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_event_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."
)
if contextvars is not None:
# Wrapping context in list so it can be reassigned from within
# `main_wrap`.
context = [contextvars.copy_context()]
else:
context = None
# 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
if contextvars is not None:
_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
if sys.version_info >= (3, 7, 0):
tasks = asyncio.all_tasks(loop)
else:
tasks = asyncio.Task.all_tasks(loop)
for task in tasks:
task.cancel()
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
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:
result = await self.awaitable(*args, **kwargs)
else:
result = await self.awaitable(*args, **kwargs)
except Exception as e:
call_result.set_exception(e)
else:
call_result.set_result(result)
finally:
del self.launch_map[current_task]
if context is not None:
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 they've set ASGI_THREADS, update the default asyncio executor for now
if "ASGI_THREADS" in os.environ:
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 = {}
# Storage for main event loop references
threadlocal = threading.local()
# Single-thread executor for thread-sensitive code
single_thread_executor = ThreadPoolExecutor(max_workers=1)
def __init__(self, func, thread_sensitive=False):
self.func = func
functools.update_wrapper(self, func)
self._thread_sensitive = thread_sensitive
self._is_coroutine = asyncio.coroutines._is_coroutine
try:
self.__self__ = func.__self__
except AttributeError:
pass
async def __call__(self, *args, **kwargs):
loop = asyncio.get_event_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
else:
# Otherwise, we run it in a fixed single thread
executor = self.single_thread_executor
else:
executor = None # Use default
if contextvars is not None:
context = contextvars.copy_context()
child = functools.partial(self.func, *args, **kwargs)
func = context.run
args = (child,)
kwargs = {}
else:
func = self.func
# 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)
if contextvars is not None:
_restore_context(context)
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
# 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:
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():
"""
Cross-version implementation of asyncio.current_task()
Returns None if there is no task.
"""
try:
if hasattr(asyncio, "current_task"):
# Python 3.7 and up
return asyncio.current_task()
else:
# Python 3.6
return asyncio.Task.current_task()
except RuntimeError:
return None
# Lowercase is more sensible for most things
sync_to_async = SyncToAsync
async_to_sync = AsyncToSync

View File

@@ -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()

View File

@@ -0,0 +1,128 @@
# 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
import sys
from types import TracebackType
from typing import Any, Optional, Type # noqa
PY_37 = sys.version_info >= (3, 7)
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 = 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
def current_task(loop: asyncio.AbstractEventLoop) -> "asyncio.Task[Any]":
if PY_37:
task = asyncio.current_task(loop=loop) # type: ignore
else:
task = asyncio.Task.current_task(loop=loop)
if task is None:
# this should be removed, tokio must use register_task and family API
if hasattr(loop, "current_task"):
task = loop.current_task() # type: ignore
return task

View File

@@ -0,0 +1,145 @@
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
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", ""),
"PATH_INFO": scope["path"],
"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
]
# 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
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)
self.sync_send(
{"type": "http.response.body", "body": output, "more_body": True}
)
# Close connection
if not self.response_started:
self.response_started = True
self.sync_send(self.response_start)
self.sync_send({"type": "http.response.body"})

View File

@@ -0,0 +1 @@
pip

View File

@@ -0,0 +1,21 @@
This packge contains a modified version of ca-bundle.crt:
ca-bundle.crt -- Bundle of CA Root Certificates
Certificate data from Mozilla as of: Thu Nov 3 19:04:19 2011#
This is a bundle of X.509 certificates of public Certificate Authorities
(CA). These were automatically extracted from Mozilla's root certificates
file (certdata.txt). This file can be found in the mozilla source tree:
http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1#
It contains the certificates in PEM format and therefore
can be directly used with curl / libcurl / php_curl, or with
an Apache+mod_ssl webserver for SSL client authentication.
Just configure this file as the SSLCACertificateFile.#
***** BEGIN LICENSE BLOCK *****
This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
one at http://mozilla.org/MPL/2.0/.
***** END LICENSE BLOCK *****
@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $

View File

@@ -0,0 +1,82 @@
Metadata-Version: 2.1
Name: certifi
Version: 2020.6.20
Summary: Python package for providing Mozilla's CA Bundle.
Home-page: https://certifiio.readthedocs.io/en/latest/
Author: Kenneth Reitz
Author-email: me@kennethreitz.com
License: MPL-2.0
Project-URL: Documentation, https://certifiio.readthedocs.io/en/latest/
Project-URL: Source, https://github.com/certifi/python-certifi
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
Classifier: Natural Language :: English
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Certifi: Python SSL Certificates
================================
`Certifi`_ provides Mozilla's carefully curated collection of Root Certificates for
validating the trustworthiness of SSL certificates while verifying the identity
of TLS hosts. It has been extracted from the `Requests`_ project.
Installation
------------
``certifi`` is available on PyPI. Simply install it with ``pip``::
$ pip install certifi
Usage
-----
To reference the installed certificate authority (CA) bundle, you can use the
built-in function::
>>> import certifi
>>> certifi.where()
'/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
Or from the command line::
$ python -m certifi
/usr/local/lib/python3.7/site-packages/certifi/cacert.pem
Enjoy!
1024-bit Root Certificates
~~~~~~~~~~~~~~~~~~~~~~~~~~
Browsers and certificate authorities have concluded that 1024-bit keys are
unacceptably weak for certificates, particularly root certificates. For this
reason, Mozilla has removed any weak (i.e. 1024-bit key) certificate from its
bundle, replacing it with an equivalent strong (i.e. 2048-bit or greater key)
certificate from the same CA. Because Mozilla removed these certificates from
its bundle, ``certifi`` removed them as well.
In previous versions, ``certifi`` provided the ``certifi.old_where()`` function
to intentionally re-add the 1024-bit roots back into your bundle. This was not
recommended in production and therefore was removed at the end of 2018.
.. _`Certifi`: https://certifiio.readthedocs.io/en/latest/
.. _`Requests`: https://requests.readthedocs.io/en/master/
Addition/Removal of Certificates
--------------------------------
Certifi does not support any addition/removal or other modification of the
CA trust store content. This project is intended to provide a reliable and
highly portable root of trust to python deployments. Look to upstream projects
for methods to use alternate trust.

View File

@@ -0,0 +1,13 @@
certifi-2020.6.20.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
certifi-2020.6.20.dist-info/LICENSE,sha256=anCkv2sBABbVmmS4rkrY3H9e8W8ftFPMLs13HFo0ETE,1048
certifi-2020.6.20.dist-info/METADATA,sha256=_0lH4pmUKzXqjJAq6fIlE4JB2g1CFLPpjpwwOsqNqwk,2944
certifi-2020.6.20.dist-info/RECORD,,
certifi-2020.6.20.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
certifi-2020.6.20.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
certifi/__init__.py,sha256=u1E_DrSGj_nnEkK5VglvEqP8D80KpghLVWL0A_pq41A,62
certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
certifi/__pycache__/__init__.cpython-38.pyc,,
certifi/__pycache__/__main__.cpython-38.pyc,,
certifi/__pycache__/core.cpython-38.pyc,,
certifi/cacert.pem,sha256=GhT24f0R7_9y4YY_hkXwkO7BthZhRGDCEMO348E9S14,282394
certifi/core.py,sha256=V0uyxKOYdz6ulDSusclrLmjbPgOXsD0BnEf0SQ7OnoE,2303

View File

@@ -0,0 +1,6 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.34.2)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any

View File

@@ -0,0 +1 @@
certifi

View File

@@ -0,0 +1,3 @@
from .core import contents, where
__version__ = "2020.06.20"

View File

@@ -0,0 +1,12 @@
import argparse
from certifi import contents, where
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--contents", action="store_true")
args = parser.parse_args()
if args.contents:
print(contents())
else:
print(where())

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
"""
certifi.py
~~~~~~~~~~
This module returns the installation location of cacert.pem or its contents.
"""
import os
try:
from importlib.resources import path as get_path, read_text
_CACERT_CTX = None
_CACERT_PATH = None
def where():
# This is slightly terrible, but we want to delay extracting the file
# in cases where we're inside of a zipimport situation until someone
# actually calls where(), but we don't want to re-extract the file
# on every call of where(), so we'll do it once then store it in a
# global variable.
global _CACERT_CTX
global _CACERT_PATH
if _CACERT_PATH is None:
# This is slightly janky, the importlib.resources API wants you to
# manage the cleanup of this file, so it doesn't actually return a
# path, it returns a context manager that will give you the path
# when you enter it and will do any cleanup when you leave it. In
# the common case of not needing a temporary file, it will just
# return the file system location and the __exit__() is a no-op.
#
# We also have to hold onto the actual context manager, because
# it will do the cleanup whenever it gets garbage collected, so
# we will also store that at the global level as well.
_CACERT_CTX = get_path("certifi", "cacert.pem")
_CACERT_PATH = str(_CACERT_CTX.__enter__())
return _CACERT_PATH
except ImportError:
# This fallback will work for Python versions prior to 3.7 that lack the
# importlib.resources module but relies on the existing `where` function
# so won't address issues with environments like PyOxidizer that don't set
# __file__ on modules.
def read_text(_module, _path, encoding="ascii"):
with open(where(), "r", encoding=encoding) as data:
return data.read()
# If we don't have importlib.resources, then we will just do the old logic
# of assuming we're on the filesystem and munge the path directly.
def where():
f = os.path.dirname(__file__)
return os.path.join(f, "cacert.pem")
def contents():
return read_text("certifi", "cacert.pem", encoding="ascii")

View File

@@ -0,0 +1,318 @@
#!/usr/bin/env python
from __future__ import with_statement
import logging
import optparse
import os
import os.path
import re
import shutil
import subprocess
import sys
import itertools
__version__ = '0.5.4'
logger = logging.getLogger()
env_bin_dir = 'bin'
if sys.platform == 'win32':
env_bin_dir = 'Scripts'
class UserError(Exception):
pass
def _dirmatch(path, matchwith):
"""Check if path is within matchwith's tree.
>>> _dirmatch('/home/foo/bar', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar2', '/home/foo/bar')
False
>>> _dirmatch('/home/foo/bar2/etc', '/home/foo/bar')
False
"""
matchlen = len(matchwith)
if (path.startswith(matchwith)
and path[matchlen:matchlen + 1] in [os.sep, '']):
return True
return False
def _virtualenv_sys(venv_path):
"obtain version and path info from a virtualenv."
executable = os.path.join(venv_path, env_bin_dir, 'python')
# Must use "executable" as the first argument rather than as the
# keyword argument "executable" to get correct value from sys.path
p = subprocess.Popen([executable,
'-c', 'import sys;'
'print (sys.version[:3]);'
'print ("\\n".join(sys.path));'],
env={},
stdout=subprocess.PIPE)
stdout, err = p.communicate()
assert not p.returncode and stdout
lines = stdout.decode('utf-8').splitlines()
return lines[0], list(filter(bool, lines[1:]))
def clone_virtualenv(src_dir, dst_dir):
if not os.path.exists(src_dir):
raise UserError('src dir %r does not exist' % src_dir)
if os.path.exists(dst_dir):
raise UserError('dest dir %r exists' % dst_dir)
#sys_path = _virtualenv_syspath(src_dir)
logger.info('cloning virtualenv \'%s\' => \'%s\'...' %
(src_dir, dst_dir))
shutil.copytree(src_dir, dst_dir, symlinks=True,
ignore=shutil.ignore_patterns('*.pyc'))
version, sys_path = _virtualenv_sys(dst_dir)
logger.info('fixing scripts in bin...')
fixup_scripts(src_dir, dst_dir, version)
has_old = lambda s: any(i for i in s if _dirmatch(i, src_dir))
if has_old(sys_path):
# only need to fix stuff in sys.path if we have old
# paths in the sys.path of new python env. right?
logger.info('fixing paths in sys.path...')
fixup_syspath_items(sys_path, src_dir, dst_dir)
v_sys = _virtualenv_sys(dst_dir)
remaining = has_old(v_sys[1])
assert not remaining, v_sys
fix_symlink_if_necessary(src_dir, dst_dir)
def fix_symlink_if_necessary(src_dir, dst_dir):
#sometimes the source virtual environment has symlinks that point to itself
#one example is $OLD_VIRTUAL_ENV/local/lib points to $OLD_VIRTUAL_ENV/lib
#this function makes sure
#$NEW_VIRTUAL_ENV/local/lib will point to $NEW_VIRTUAL_ENV/lib
#usually this goes unnoticed unless one tries to upgrade a package though pip, so this bug is hard to find.
logger.info("scanning for internal symlinks that point to the original virtual env")
for dirpath, dirnames, filenames in os.walk(dst_dir):
for a_file in itertools.chain(filenames, dirnames):
full_file_path = os.path.join(dirpath, a_file)
if os.path.islink(full_file_path):
target = os.path.realpath(full_file_path)
if target.startswith(src_dir):
new_target = target.replace(src_dir, dst_dir)
logger.debug('fixing symlink in %s' % (full_file_path,))
os.remove(full_file_path)
os.symlink(new_target, full_file_path)
def fixup_scripts(old_dir, new_dir, version, rewrite_env_python=False):
bin_dir = os.path.join(new_dir, env_bin_dir)
root, dirs, files = next(os.walk(bin_dir))
pybinre = re.compile(r'pythonw?([0-9]+(\.[0-9]+(\.[0-9]+)?)?)?$')
for file_ in files:
filename = os.path.join(root, file_)
if file_ in ['python', 'python%s' % version, 'activate_this.py']:
continue
elif file_.startswith('python') and pybinre.match(file_):
# ignore other possible python binaries
continue
elif file_.endswith('.pyc'):
# ignore compiled files
continue
elif file_ == 'activate' or file_.startswith('activate.'):
fixup_activate(os.path.join(root, file_), old_dir, new_dir)
elif os.path.islink(filename):
fixup_link(filename, old_dir, new_dir)
elif os.path.isfile(filename):
fixup_script_(root, file_, old_dir, new_dir, version,
rewrite_env_python=rewrite_env_python)
def fixup_script_(root, file_, old_dir, new_dir, version,
rewrite_env_python=False):
old_shebang = '#!%s/bin/python' % os.path.normcase(os.path.abspath(old_dir))
new_shebang = '#!%s/bin/python' % os.path.normcase(os.path.abspath(new_dir))
env_shebang = '#!/usr/bin/env python'
filename = os.path.join(root, file_)
with open(filename, 'rb') as f:
if f.read(2) != b'#!':
# no shebang
return
f.seek(0)
lines = f.readlines()
if not lines:
# warn: empty script
return
def rewrite_shebang(version=None):
logger.debug('fixing %s' % filename)
shebang = new_shebang
if version:
shebang = shebang + version
shebang = (shebang + '\n').encode('utf-8')
with open(filename, 'wb') as f:
f.write(shebang)
f.writelines(lines[1:])
try:
bang = lines[0].decode('utf-8').strip()
except UnicodeDecodeError:
# binary file
return
# This takes care of the scheme in which shebang is of type
# '#!/venv/bin/python3' while the version of system python
# is of type 3.x e.g. 3.5.
short_version = bang[len(old_shebang):]
if not bang.startswith('#!'):
return
elif bang == old_shebang:
rewrite_shebang()
elif (bang.startswith(old_shebang)
and bang[len(old_shebang):] == version):
rewrite_shebang(version)
elif (bang.startswith(old_shebang)
and short_version
and bang[len(old_shebang):] == short_version):
rewrite_shebang(short_version)
elif rewrite_env_python and bang.startswith(env_shebang):
if bang == env_shebang:
rewrite_shebang()
elif bang[len(env_shebang):] == version:
rewrite_shebang(version)
else:
# can't do anything
return
def fixup_activate(filename, old_dir, new_dir):
logger.debug('fixing %s' % filename)
with open(filename, 'rb') as f:
data = f.read().decode('utf-8')
data = data.replace(old_dir, new_dir)
with open(filename, 'wb') as f:
f.write(data.encode('utf-8'))
def fixup_link(filename, old_dir, new_dir, target=None):
logger.debug('fixing %s' % filename)
if target is None:
target = os.readlink(filename)
origdir = os.path.dirname(os.path.abspath(filename)).replace(
new_dir, old_dir)
if not os.path.isabs(target):
target = os.path.abspath(os.path.join(origdir, target))
rellink = True
else:
rellink = False
if _dirmatch(target, old_dir):
if rellink:
# keep relative links, but don't keep original in case it
# traversed up out of, then back into the venv.
# so, recreate a relative link from absolute.
target = target[len(origdir):].lstrip(os.sep)
else:
target = target.replace(old_dir, new_dir, 1)
# else: links outside the venv, replaced with absolute path to target.
_replace_symlink(filename, target)
def _replace_symlink(filename, newtarget):
tmpfn = "%s.new" % filename
os.symlink(newtarget, tmpfn)
os.rename(tmpfn, filename)
def fixup_syspath_items(syspath, old_dir, new_dir):
for path in syspath:
if not os.path.isdir(path):
continue
path = os.path.normcase(os.path.abspath(path))
if _dirmatch(path, old_dir):
path = path.replace(old_dir, new_dir, 1)
if not os.path.exists(path):
continue
elif not _dirmatch(path, new_dir):
continue
root, dirs, files = next(os.walk(path))
for file_ in files:
filename = os.path.join(root, file_)
if filename.endswith('.pth'):
fixup_pth_file(filename, old_dir, new_dir)
elif filename.endswith('.egg-link'):
fixup_egglink_file(filename, old_dir, new_dir)
def fixup_pth_file(filename, old_dir, new_dir):
logger.debug('fixup_pth_file %s' % filename)
with open(filename, 'r') as f:
lines = f.readlines()
has_change = False
for num, line in enumerate(lines):
line = (line.decode('utf-8') if hasattr(line, 'decode') else line).strip()
if not line or line.startswith('#') or line.startswith('import '):
continue
elif _dirmatch(line, old_dir):
lines[num] = line.replace(old_dir, new_dir, 1)
has_change = True
if has_change:
with open(filename, 'w') as f:
payload = os.linesep.join([l.strip() for l in lines]) + os.linesep
f.write(payload)
def fixup_egglink_file(filename, old_dir, new_dir):
logger.debug('fixing %s' % filename)
with open(filename, 'rb') as f:
link = f.read().decode('utf-8').strip()
if _dirmatch(link, old_dir):
link = link.replace(old_dir, new_dir, 1)
with open(filename, 'wb') as f:
link = (link + '\n').encode('utf-8')
f.write(link)
def main():
parser = optparse.OptionParser("usage: %prog [options]"
" /path/to/existing/venv /path/to/cloned/venv")
parser.add_option('-v',
action="count",
dest='verbose',
default=False,
help='verbosity')
options, args = parser.parse_args()
try:
old_dir, new_dir = args
except ValueError:
print("virtualenv-clone %s" % (__version__,))
parser.error("not enough arguments given.")
old_dir = os.path.realpath(old_dir)
new_dir = os.path.realpath(new_dir)
loglevel = (logging.WARNING, logging.INFO, logging.DEBUG)[min(2,
options.verbose)]
logging.basicConfig(level=loglevel, format='%(message)s')
try:
clone_virtualenv(old_dir, new_dir)
except UserError:
e = sys.exc_info()[1]
parser.error(str(e))
if __name__ == '__main__':
main()

View File

@@ -0,0 +1 @@
__version__ = "1.9.2"

View File

@@ -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]

View File

@@ -0,0 +1,409 @@
from random import randint
from django.template import Template
from django.template.defaultfilters import slugify
from django.template.loader import render_to_string
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, *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 = None
css_class = kwargs.get("css_class", "")
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),
}
)
if hasattr(self, "wrapper_class"):
extra_context["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):
template = "%s/layout/field_with_buttons.html"
field_template = "%s/field.html"
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)
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 render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
content = ""
# accordion group needs the parent div id to set `data-parent` (I don't
# know why). This needs to be a unique id
if not self.css_id:
self.css_id = "-".join(["accordion", str(randint(1000, 9999))])
# 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"

View File

@@ -0,0 +1,6 @@
import django
if django.VERSION < (3, 0):
from django.utils.lru_cache import lru_cache # noqa: F401
else:
from functools import lru_cache # noqa: F401

View File

@@ -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

View File

@@ -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::
url(r'^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

View File

@@ -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)

View File

@@ -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)

View File

@@ -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>

View File

@@ -0,0 +1,3 @@
<div class="accordion" id="{{ accordion.css_id }}">
{{ content|safe }}
</div>

View File

@@ -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 %}

View File

@@ -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 %}

View File

@@ -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 %}

View File

@@ -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 %}

View File

@@ -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 %}

View File

@@ -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">&times;</button>{% endif %}
{{ content|safe }}
</div>

View File

@@ -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 }}
/>

View File

@@ -0,0 +1 @@
<button {{ button.flat_attrs|safe }}>{{ button.content|safe }}</button>

View File

@@ -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 have changed in this diff Show More