code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
import os
import sys
# Tell distutils to put the data_files in platform-specific installation
# locations. See here for an explanation:
# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d... | Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# test_client modeltest urls
(r'^test_client/', include('modeltests.test_client.urls')),
# Always provide the auth system login and logout views
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'})... | Python |
#!/usr/bin/env python
import os, sys, traceback
import unittest
MODEL_TESTS_DIR_NAME = 'modeltests'
REGRESSION_TESTS_DIR_NAME = 'regressiontests'
TEST_DATABASE_NAME = 'django_test_db'
TEST_TEMPLATE_DIR = 'templates'
MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME)
REGRESSION_TEST_DIR = ... | Python |
r"""
>>> floatformat(7.7)
'7.7'
>>> floatformat(7.0)
'7'
>>> floatformat(0.7)
'0.7'
>>> floatformat(0.07)
'0.1'
>>> floatformat(0.007)
'0.0'
>>> floatformat(0.0)
'0'
>>> floatformat(7.7,3)
'7.700'
>>> floatformat(6.000000,3)
'6.000'
>>> floatformat(13.1031,-3)
'13.103'
>>> floatformat(11.1197, -2)
'11.12'
>>> floatform... | Python |
# Quick tests for the markup templatetags (django.contrib.markup)
from django.template import Template, Context, add_to_builtins
import re
import unittest
add_to_builtins('django.contrib.markup.templatetags.markup')
class Templates(unittest.TestCase):
def test_textile(self):
try:
import texti... | Python |
from django.db import models
class Place(models.Model):
name = models.CharField(maxlength=50)
address = models.CharField(maxlength=80)
def __str__(self):
return "%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(Place)
serves_hot_dogs = models.BooleanF... | Python |
from django.db import models
class Poll(models.Model):
question = models.CharField(maxlength=200)
def __str__(self):
return "Q: %s " % self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(maxlength=200)
def __str__(self):
return "Choi... | Python |
"""
A test spanning all the capabilities of all the serializers.
This class sets up a model for each model field type
(except for image types, because of the PIL dependency).
"""
from django.db import models
from django.contrib.contenttypes.models import ContentType
# The following classes are for testing basic dat... | Python |
"""
A test spanning all the capabilities of all the serializers.
This class defines sample data and a dynamically generated
test case that is capable of testing the capabilities of
the serializers. This includes all valid data values, plus
forward, backwards and self references.
"""
import unittest, datetime
from ... | Python |
"Unit tests for reverse URL lookup"
from django.core.urlresolvers import reverse_helper, NoReverseMatch
import re, unittest
test_data = (
('^places/(\d+)/$', 'places/3/', [3], {}),
('^places/(\d+)/$', 'places/3/', ['3'], {}),
('^places/(\d+)/$', NoReverseMatch, ['a'], {}),
('^places/(\d+)/$', NoRevers... | Python |
# Unit tests for typecast functions in django.db.backends.util
from django.db.backends import util as typecasts
import datetime, unittest
TEST_CASES = {
'typecast_date': (
('', None),
(None, None),
('2005-08-11', datetime.date(2005, 8, 11)),
('1990-01-01', datetime.date(1990, 1, 1)... | Python |
from django.db import models
# If ticket #1578 ever slips back in, these models will not be able to be
# created (the field names being lower-cased versions of their opposite
# classes is important here).
class First(models.Model):
second = models.IntegerField()
class Second(models.Model):
first = models.For... | Python |
from django.db import models
class Foo(models.Model):
name = models.CharField(maxlength=50)
def __str__(self):
return "Foo %s" % self.name
class Bar(models.Model):
name = models.CharField(maxlength=50)
normal = models.ForeignKey(Foo, related_name='normal_foo')
fwd = models.ForeignKey("Whi... | Python |
from django.conf.urls.defaults import *
from regressiontests.templates import views
urlpatterns = patterns('',
# Test urls for testing reverse lookups
(r'^$', views.index),
(r'^client/(\d+)/$', views.client),
(r'^client/(\d+)/(?P<action>[^/]+)/$', views.client_action),
)
| Python |
# -*- coding: utf-8 -*-
from django.conf import settings
if __name__ == '__main__':
# When running this file in isolation, we need to set up the configuration
# before importing 'template'.
settings.configure()
from django import template
from django.template import loader
from django.utils.translation im... | Python |
# Fake views for testing url reverse lookup
def index(request):
pass
def client(request, id):
pass
def client_action(request, id, action):
pass
| Python |
import unittest
from django.template import Template, Context, add_to_builtins
add_to_builtins('django.contrib.humanize.templatetags.humanize')
class HumanizeTests(unittest.TestCase):
def humanize_tester(self, test_list, result_list, method):
# Using max below ensures we go through both lists
# H... | Python |
# -*- coding: utf-8 -*-
r"""
>>> from django.newforms import *
>>> import datetime
>>> import re
###########
# Widgets #
###########
Each Widget class corresponds to an HTML form widget. A Widget knows how to
render itself, given a field name and some data. Widgets don't perform
validation.
# TextInput Widget ######... | Python |
"""
Regression tests for initial SQL insertion.
"""
from django.db import models
class Simple(models.Model):
name = models.CharField(maxlength = 50)
__test__ = {'API_TESTS':""}
# NOTE: The format of the included SQL file for this test suite is important.
# It must end with a trailing newline in order to test th... | Python |
"""
Admin options
Test invalid and valid admin options to make sure that
model validation is working properly.
"""
from django.db import models
model_errors = ""
# TODO: Invalid admin options should not cause a metaclass error
##This should fail gracefully but is causing a metaclass error
#class BadAdminOption(mode... | Python |
import tempfile
from django.db import models
class Photo(models.Model):
title = models.CharField(maxlength=30)
image = models.FileField(upload_to=tempfile.gettempdir())
# Support code for the tests; this keeps track of how many times save() gets
# called on each instance.
def __init__(self, *a... | Python |
"""
Tests for file field behavior, and specifically #639, in which Model.save() gets
called *again* for each FileField. This test will fail if calling an
auto-manipulator's save() method causes Model.save() to be called more than once.
"""
import os
import unittest
from regressiontests.bug639.models import Photo
from ... | Python |
"""
Unit-tests for the dispatch project
"""
from test_dispatcher import *
from test_robustapply import *
from test_saferef import *
| Python |
"""Unit-tests for the dispatch project
"""
| Python |
"""
# Tests for stuff in django.utils.datastructures.
>>> from django.utils.datastructures import *
### MergeDict #################################################################
>>> d1 = {'chris':'cool','camri':'cute','cotton':'adorable','tulip':'snuggable', 'twoofme':'firstone'}
>>> d2 = {'chris2':'cool2','camri2... | Python |
r"""
>>> format(my_birthday, '')
''
>>> format(my_birthday, 'a')
'p.m.'
>>> format(my_birthday, 'A')
'PM'
>>> format(my_birthday, 'd')
'08'
>>> format(my_birthday, 'j')
'8'
>>> format(my_birthday, 'l')
'Sunday'
>>> format(my_birthday, 'L')
'False'
>>> format(my_birthday, 'm')
'07'
>>> format(my_birthday, 'M')
'Jul'
>>>... | Python |
"""
###################
# Empty QueryDict #
###################
>>> q = QueryDict('')
>>> q['foo']
Traceback (most recent call last):
...
MultiValueDictKeyError: "Key 'foo' not found in <MultiValueDict: {}>"
>>> q['something'] = 'bar'
Traceback (most recent call last):
...
AttributeError: This QueryDict instance is ... | Python |
"""
23. Giving models a custom manager
You can use a custom ``Manager`` in a particular model by extending the base
``Manager`` class and instantiating your custom ``Manager`` in your model.
There are two reasons you might want to customize a ``Manager``: to add extra
``Manager`` methods, and/or to modify the initial... | Python |
"""
25. Reverse lookups
This demonstrates the reverse lookup features of the database API.
"""
from django.db import models
class User(models.Model):
name = models.CharField(maxlength=200)
def __str__(self):
return self.name
class Poll(models.Model):
question = models.CharField(maxlength=200)
... | Python |
"""
17. Custom column/table names
If your database column name is different than your model attribute, use the
``db_column`` parameter. Note that you'll use the field's name, not its column
name, in API usage.
If your database table name is different than your model name, use the
``db_table`` Meta attribute. This has... | Python |
"""
10. One-to-one relationships
To define a one-to-one relationship, use ``OneToOneField()``.
In this example, a ``Place`` optionally can be a ``Restaurant``.
"""
from django.db import models
class Place(models.Model):
name = models.CharField(maxlength=50)
address = models.CharField(maxlength=80)
def ... | Python |
"""
39. Empty model tests
These test that things behave sensibly for the rare corner-case of a model with
no fields.
"""
from django.db import models
class Empty(models.Model):
pass
__test__ = {'API_TESTS':"""
>>> m = Empty()
>>> m.id
>>> m.save()
>>> m2 = Empty()
>>> m2.save()
>>> len(Empty.objects.all())
2
>>... | Python |
"""
2. Adding __str__() to models
Although it's not a strict requirement, each model should have a ``__str__()``
method to return a "human-readable" representation of the object. Do this not
only for your own sanity when dealing with the interactive prompt, but also
because objects' representations are used throughout... | Python |
"""
21. Specifying 'choices' for a field
Most fields take a ``choices`` parameter, which should be a tuple of tuples
specifying which are the valid values for that field.
For each field that has ``choices``, a model instance gets a
``get_fieldname_display()`` method, where ``fieldname`` is the name of the
field. This... | Python |
"""
11. Relating an object to itself, many-to-one
To define a many-to-one relationship between a model and itself, use
``ForeignKey('self')``.
In this example, a ``Category`` is related to itself. That is, each
``Category`` has a parent ``Category``.
Set ``related_name`` to designate what the reverse relationship is... | Python |
"""
32. Callable defaults
You can pass callable objects as the ``default`` parameter to a field. When
the object is created without an explicit value passed in, Django will call
the method to determine the default value.
This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
field.
"""
from ... | Python |
"""
40. Tests for select_related()
``select_related()`` follows all relationships and pre-caches any foreign key
values so that complex trees can be fetched in a single query. However, this
isn't always a good idea, so the ``depth`` argument control how many "levels"
the select-related behavior will traverse.
"""
fro... | Python |
"""
12. Relating a model to another model more than once
In this example, a ``Person`` can have a ``mother`` and ``father`` -- both of
which are other ``Person`` objects.
Set ``related_name`` to designate what the reverse relationship is called.
"""
from django.db import models
class Person(models.Model):
full_... | Python |
"""
26. Invalid models
This example exists purely to point out errors in models.
"""
from django.db import models
class FieldErrors(models.Model):
charfield = models.CharField()
floatfield = models.FloatField()
filefield = models.FileField()
prepopulate = models.CharField(maxlength=10, prepopulate_fr... | Python |
"""
22. Using properties on models
Use properties on models just like on any other Python object.
"""
from django.db import models
class Person(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
def _get_full_name(self):
return "%s %s" % (self.f... | Python |
"""
7. The lookup API
This demonstrates features of the database API.
"""
from django.db import models
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateTimeField()
class Meta:
ordering = ('-pub_date', 'headline')
def __str__(self):
return ... | Python |
"""
14. Using a custom primary key
By default, Django adds an ``"id"`` field to each model. But you can override
this behavior by explicitly adding ``primary_key=True`` to a field.
"""
from django.db import models
class Employee(models.Model):
employee_code = models.CharField(maxlength=10, primary_key=True,
... | Python |
"""
8. get_latest_by
Models can have a ``get_latest_by`` attribute, which should be set to the name
of a DateField or DateTimeField. If ``get_latest_by`` exists, the model's
manager will get a ``latest()`` method, which will return the latest object in
the database according to that field. "Latest" means "having the d... | Python |
"""
24. Mutually referential many-to-one relationships
To define a many-to-one relationship, use ``ForeignKey()`` .
"""
from django.db.models import *
class Parent(Model):
name = CharField(maxlength=100, core=True)
bestchild = ForeignKey("Child", null=True, related_name="favoured_by")
class Child(Model):
... | Python |
"""
41. Serialization
``django.core.serializers`` provides interfaces to converting Django querysets
to and from "flat" data (i.e. strings).
"""
from django.db import models
class Category(models.Model):
name = models.CharField(maxlength=20)
class Meta:
ordering = ('name',)
def __str__(self):
... | Python |
"""
4. Many-to-one relationships
To define a many-to-one relationship, use ``ForeignKey()`` .
"""
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
email = models.EmailField()
def __str__(self):
r... | Python |
"""
19. OR lookups
To perform an OR lookup, or a lookup that combines ANDs and ORs,
combine QuerySet objects using & and | operators.
Alternatively, use positional arguments, and pass one or more expressions
of clauses using the variable ``django.db.models.Q`` (or any object with
a get_sql method).
"""
from django... | Python |
"""
3. Giving models custom methods
Any method you add to a model will be available to instances.
"""
from django.db import models
import datetime
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateField()
def __str__(self):
return self.headline
de... | Python |
"""
36. Generating HTML forms from models
Django provides shortcuts for creating Form objects from a model class and a
model instance.
The function django.newforms.form_for_model() takes a model class and returns
a Form that is tied to the model. This Form works just like any other Form,
with one additional method: s... | Python |
"""
27. Default manipulators
Each model gets an AddManipulator and ChangeManipulator by default.
"""
from django.db import models
class Musician(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
def __str__(self):
return "%s %s" % (self.first_n... | Python |
"""
18. Using SQL reserved names
Need to use a reserved SQL name as a column name or table name? Need to include
a hyphen in a column or table name? No problem. Django quotes names
appropriately behind the scenes, so your database won't complain about
reserved-name usage.
"""
from django.db import models
class Thing... | Python |
"""
XX. Model inheritance
Model inheritance isn't yet supported.
"""
from django.db import models
class Place(models.Model):
name = models.CharField(maxlength=50)
address = models.CharField(maxlength=80)
def __str__(self):
return "%s the place" % self.name
class Restaurant(Place):
serves_ho... | Python |
"""
34. Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A generic foreign key can point to any object,
be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from ... | Python |
"""
35. DB-API Shortcuts
get_object_or_404 is a shortcut function to be used in view functions for
performing a get() lookup and raising a Http404 exception if a DoesNotExist
exception was rasied during the get() call.
get_list_or_404 is a shortcut function to be used in view functions for
performing a filter() looku... | Python |
"""
13. Adding hooks before/after saving and deleting
To execute arbitrary code around ``save()`` and ``delete()``, just subclass
the methods.
"""
from django.db import models
class Person(models.Model):
first_name = models.CharField(maxlength=20)
last_name = models.CharField(maxlength=20)
def __str__(s... | Python |
"""
1. Bare-bones model
This is a basic model with only two non-primary-key fields.
"""
from django.db import models
class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline')
pub_date = models.DateTimeField()
class Meta:
ordering = ('pub_date','headline'... | Python |
"""
16. Many-to-one relationships that can be null
To define a many-to-one relationship that can have a null foreign key, use
``ForeignKey()`` with ``null=True`` .
"""
from django.db import models
class Reporter(models.Model):
name = models.CharField(maxlength=30)
def __str__(self):
return self.name... | Python |
"""
15. Transactions
Django handles transactions in three different ways. The default is to commit
each transaction upon a write, but you can decorate a function to get
commit-on-success behavior. Alternatively, you can manage the transaction
manually.
"""
from django.db import models
class Reporter(models.Model):
... | Python |
"""
31. Validation
This is an experimental feature!
Each model instance has a validate() method that returns a dictionary of
validation errors in the instance's fields. This method has a side effect
of converting each field to its appropriate Python data type.
"""
from django.db import models
class Person(models.Mo... | Python |
"""
33. get_or_create()
get_or_create() does what it says: it tries to look up an object with the given
parameters. If an object isn't found, it creates one with the given parameters.
"""
from django.db import models
class Person(models.Model):
first_name = models.CharField(maxlength=100)
last_name = models.... | Python |
"""
28. Many-to-many relationships between the same two tables
In this example, A Person can have many friends, who are also people. Friendship is a
symmetrical relationship - if I am your friend, you are my friend.
A person can also have many idols - but while I may idolize you, you may not think
the same of me. 'Id... | Python |
"""
6. Specifying ordering
Specify default ordering for a model using the ``ordering`` attribute, which
should be a list or tuple of field names. This tells Django how to order the
results of ``get_list()`` and other similar functions.
If a field name in ``ordering`` starts with a hyphen, that field will be
ordered i... | Python |
"""
5. Many-to-many relationships
To define a many-to-many relationship, use ManyToManyField().
In this example, an article can be published in multiple publications,
and a publication has multiple articles.
"""
from django.db import models
class Publication(models.Model):
title = models.CharField(maxlength=30)... | Python |
"""
30. Object pagination
Django provides a framework for paginating a list of objects in a few lines
of code. This is often useful for dividing search results or long lists of
objects into easily readable pages.
"""
from django.db import models
class Article(models.Model):
headline = models.CharField(maxlength=... | Python |
"""
20. Multiple many-to-many relationships between the same two tables
In this example, an Article can have many Categories (as "primary") and many
Categories (as "secondary").
Set ``related_name`` to designate what the reverse relationship is called.
"""
from django.db import models
class Category(models.Model):
... | Python |
"""
9. Many-to-many relationships via an intermediary table
For many-to-many relationships that need extra fields on the intermediary
table, use an intermediary model.
In this example, an ``Article`` can have multiple ``Reporter``s, and each
``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field... | Python |
"""
29. Many-to-many and many-to-one relationships to the same table
Make sure to set ``related_name`` if you use relationships to the same table.
"""
from django.db import models
class User(models.Model):
username = models.CharField(maxlength=20)
class Issue(models.Model):
num = models.IntegerField()
c... | Python |
"""
37. Fixtures.
Fixtures are a way of loading data into the database in bulk. Fixure data
can be stored in any serializable format (including JSON and XML). Fixtures
are identified by name, and are stored in either a directory named 'fixtures'
in the application directory, on in one of the directories named in the... | Python |
#!/usr/bin/env python
import os, sys, traceback
import unittest
MODEL_TESTS_DIR_NAME = 'modeltests'
REGRESSION_TESTS_DIR_NAME = 'regressiontests'
TEST_DATABASE_NAME = 'django_test_db'
TEST_TEMPLATE_DIR = 'templates'
MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME)
REGRESSION_TEST_DIR = ... | Python |
""" @package antlr3.dottreegenerator
@brief ANTLR3 runtime package, tree module
This module contains all support classes for AST construction and tree parsers.
"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# All rights reserved.
#
# Redistribution and use in source and binary fo... | Python |
"""ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 ... | Python |
"""ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 ... | Python |
"""ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 ... | Python |
""" @package antlr3.dottreegenerator
@brief ANTLR3 runtime package, tree module
This module contains all support classes for AST construction and tree parsers.
"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# All rights reserved.
#
# Redistribution and use in source and binary fo... | Python |
"""ANTLR3 exception hierarchy"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 c... | Python |
"""ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 ... | Python |
"""ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 ... | Python |
"""ANTLR3 runtime package"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 ... | Python |
""" @package antlr3.tree
@brief ANTLR3 runtime package, treewizard module
A utility module to create ASTs at runtime.
See <http://www.antlr.org/wiki/display/~admin/2007/07/02/Exploring+Concept+of+TreeWizard> for an overview. Note that the API of the Python implementation is slightly different.
"""
# begin[licence]
#... | Python |
"""Compatibility stuff"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# 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 mus... | Python |
""" @package antlr3.tree
@brief ANTLR3 runtime package, tree module
This module contains all support classes for AST construction and tree parsers.
"""
# begin[licence]
#
# [The "BSD licence"]
# Copyright (c) 2005-2008 Terence Parr
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or... | Python |
# bootstrapping setuptools
import ez_setup
ez_setup.use_setuptools()
import os
import sys
import textwrap
from distutils.errors import *
from distutils.command.clean import clean as _clean
from distutils.cmd import Command
from setuptools import setup
from distutils import log
from distutils.core import setup
class... | Python |
"""
Does parsing of ETag-related headers: If-None-Matches, If-Matches
Also If-Range parsing
"""
import webob
__all__ = ['AnyETag', 'NoETag', 'ETagMatcher', 'IfRange', 'NoIfRange']
class _AnyETag(object):
"""
Represents an ETag of *, or a missing ETag when matching is 'safe'
"""
def __repr__(self):
... | Python |
"""
Parses a variety of ``Accept-*`` headers.
These headers generally take the form of::
value1; q=0.5, value2; q=0
Where the ``q`` parameter is optional. In theory other parameters
exists, but this ignores them.
"""
import re
part_re = re.compile(
r',\s*([^\s;,\n]+)(?:[^,]*?;\s*q=([0-9.]*))?')
def parse... | Python |
"""
HTTP Exception
This module processes Python exceptions that relate to HTTP exceptions
by defining a set of exceptions, all subclasses of HTTPException.
Each exception, in addition to being a Python exception that can be
raised and caught, is also a WSGI application and ``webob.Response``
object.
This module defin... | Python |
"""
Contains some data structures.
"""
from webob.util.dictmixin import DictMixin
class EnvironHeaders(DictMixin):
"""An object that represents the headers as present in a
WSGI environment.
This object is a wrapper (with no internal state) for a WSGI
request object, representing the CGI-style HTTP_* ... | Python |
"""
Dict that has a callback on all updates
"""
class UpdateDict(dict):
updated = None
updated_args = None
def _updated(self):
"""
Assign to new_dict.updated to track updates
"""
updated = self.updated
if updated is not None:
args = self.updated_args
... | Python |
"""
Represents the Cache-Control header
"""
import re
from webob.updatedict import UpdateDict
token_re = re.compile(
r'([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?')
need_quote_re = re.compile(r'[^a-zA-Z0-9._-]')
class exists_property(object):
"""
Represents a property that either is listed i... | Python |
"""
Gives ``status_reasons``, a dictionary of HTTP reasons for integer status codes
"""
__all__ = ['status_reasons']
status_reasons = {
# Status Codes
# Informational
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
# Successful
200: 'OK',
201: 'Created',
202: 'Acce... | Python |
class Range(object):
"""
Represents the Range header.
This only represents ``bytes`` ranges, which are the only kind
specified in HTTP. This can represent multiple sets of ranges,
but no place else is this multi-range facility supported.
"""
def __init__(self, ranges):
for begin,... | Python |
"""
Represents the response header list as a dictionary-like object.
"""
from webob.multidict import MultiDict
try:
reversed
except NameError:
from webob.util.reversed import reversed
class HeaderDict(MultiDict):
"""
Like a MultiDict, this wraps a list. Keys are normalized
for case and whitespac... | Python |
from cStringIO import StringIO
import sys
import cgi
import urllib
import urlparse
import re
import textwrap
from Cookie import BaseCookie
from rfc822 import parsedate_tz, mktime_tz, formatdate
from datetime import datetime, date, timedelta, tzinfo
import time
import calendar
import tempfile
import warnings
from webob.... | Python |
## Backport of reversed
def reversed(seq):
return iter(list(seq)[::-1])
| Python |
"""
GZip that doesn't include the timestamp
"""
import gzip
class GzipFile(gzip.GzipFile):
def _write_gzip_header(self):
self.fileobj.write('\037\213') # magic header
self.fileobj.write('\010') # compression method
fname = self.filename[:-3]
flags = 0
... | Python |
"""
A backport of UserDict.DictMixin for pre-python-2.4
"""
__all__ = ['DictMixin']
try:
from UserDict import DictMixin
except ImportError:
class DictMixin:
# Mixin defining all dictionary methods for classes that already have
# a minimum dictionary interface including getitem, setitem, delitem... | Python |
"""
Just string.Template, backported for use with Python 2.3
"""
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
d... | Python |
#
| Python |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Gives a multi-value dictionary object (MultiDict) plus several wrappers
"""
import cgi
import copy
import sys
from webob.util.dictmixin import Dict... | Python |
from setuptools import setup, find_packages
import sys, os
version = '0.9'
setup(name='WebOb',
version=version,
description="WSGI request and response object",
long_description="""\
WebOb provides wrappers around the WSGI request environment, and an
object to help create WSGI responses.
The objects... | Python |
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pkg_resources
pkg_resources.require('WebOb')
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.