Saravanan666/pypi-org huggingface dataset:
Package: django-threadlocals
Setup/UsageInstall usingpip install django-threadlocalsAddthreadlocals.middleware.ThreadLocalMiddlewareto yourMIDDLEWARE_CLASSESsetting.
Then use it as follows:Example usage:fromthreadlocals.threadlocalsimportget_current_requestrequest=get_current_request()Caveat EmptorStoring the request in threadlocals goes against several django core developers' strong inclinations against using threadlocals.
Seethis thread on django-usersfor a more in-depth discussion.
We recommend you not do this unless you have a really good reason to do so. We feel like we had a really good
reason (the only one we've come across so far):
Having the request in threadlocals is the core piece that allowed us to build a true multi-tenant system on top of django where the site is resolved dynamically based on the current host,
and  objects are filtered based on the current host. With the current version of django, this is nearly impossible to do without the request in threadlocals.  This was a very significant and advanced undertaking, but we're happy with the results.TestsTo run tests:python tester/manage.py test
Package: django-threatmetrix
django-threatmetrix makes it easy to apply the  in your django application. You just need to do the following.InstallationInstall django-threatmetrix using easy_setup or pip:pip install django-threatmetrixadd like_button to your INSTALLED_APPS in your django settings file:INSTALLED_APPS = (
    # all
    # other
    # apps
    'threatmetrix',
)Add “THREATMETRIX_ORG_ID” setting to your django settings file with your threatmetrix org id.in settings.py:THREATMETRIX_ORG_ID = "Your org id"
THREATMETRIX_URL = "https://h.online-metrix.net" # Optional
THREATMETRIX_JS_ENABLED = True  # OptionalAdd the template tag code into your base template before the body tag.Where you need the threatmetrix tag:{% load threatmetrix %}Where ever you want your threatmetrix tag use:{% threat_metrix_tags object.value %}
Package: django-throttleandcache
FeaturesGraceful handling of errors (can fall back to cached value)Calculate results in background (requiresCelery)Readable duration strings (‘1 day’vs86400)Correct handling ofNonePer-call invalidationInstallationpip install django-throttleandcacheSet a cache backend in yoursettings.pyfile.Usagefromthrottleandcacheimportcache# Cache the result of my_function for 3 seconds.@cache('3s')defmy_function():return'whatever'If you call the function multiple timeswith the same arguments, the result
will be fetched from the cache. In order to invalidate the cache for that call,
callmy_function.invalidate()with the same arguments:my_function()my_function()# Result pulled from cachemy_function.invalidate()my_function()# Not from cacheIfCeleryis installed, you can remove the the calculation of new values from
the request/response cycle:@cache('3s',background=True)defmy_function():return'whatever'Note that, in the case of a cold cache, the value will still be calculated
synchronously. Stale values may be used while new ones are being calculated.Remember that calling the same method on multiple instances means that each
invocation will have a different first positional (self) argument:classA(object):@cache('100s')defmy_function(self):print'The method is being executed!'instance_1=A()instance_2=A()instance_1.my_function()# The original method will be invokedinstance_2.my_function()# Different "self" argument, so the method is invoked again.If you wish to cache the result across all instances, use@cacheforclass.The first argument to thecachedecorator is the timeout and can be given as
a number (of seconds) or a string. Since strings contain units, they can make
your code much more readable. Some examples are‘2s’,‘3m’,‘3m 2s’, and‘3 minutes, 2 seconds’.Thecachedecorator also accepts the following (optional) keyword arguments:using: specifies which cache to use.key_prefix: A string to prefix your cache key with.key_func: A function for deriving the cache key. This function will bepassed thefn,*args, and**kwargs.graceful: This argument specifies how errors should be handled. IfgracefulisTrueand your function raises an error, throttleandcache
will log the error and return the cached value. If no cached value exists,
the original error is raised.background: Specifies that new values should be calculated in thebackground (usingCelery).
Package: django-throttle-requests
a framework for implementing rate-limiting middleware for Django projectsOverviewThis package allows Django developers to define application-level rate-limiting rules. Often, these rules would be expressed as “max # requests within a defined time period”. E.g.:an IP address may make at most 1500 requests/dayusers with an OAuth access token may make 500 reads/hour and 200 writes/hourYou can also define leaky bucket-style rules:Allow 10 requests per minute, then every 6 seconds thereafter.FeaturesAttach rules to specific views using a decoratorSupports multiple throttle configurationsUse Django’s cache layer as the storage backend, or use Redis scripting for production-ready atomic operationsDefine request attributes to rate limit (e.g. remote IP address, username, HTTP header value, device fingerprint, etc.)Application-level rate limiting rules using fixed-bucket or generic cell rate algorithm (leaky bucket)InstallationInstall the library with pip:sudo pip install django-throttle-requestsAdd the directorythrottleto your project’sPYTHONPATH.UsageInsert the following configuration into your project’s settings:THROTTLE_ZONES = {
    'default': {
        'VARY':'throttle.zones.RemoteIP',
        'ALGORITHM': 'fixed-bucket',  # Default if not defined.
        'BUCKET_INTERVAL':15 * 60,  # Number of seconds to enforce limit.
        'BUCKET_CAPACITY':50,  # Maximum number of requests allowed within BUCKET_INTERVAL
    },
}

# Where to store request counts.
THROTTLE_BACKEND = 'throttle.backends.cache.CacheBackend'

# Optional if Redis backend is chosen ('throttle.backends.redispy.RedisBackend')
THROTTLE_REDIS_HOST = 'localhost'
THROTTLE_REDIS_PORT = 6379
THROTTLE_REDIS_DB = 0
THROTTLE_REDIS_AUTH = 'pass'

# Normally, throttling is disabled when DEBUG=True. Use this to force it to enabled.
THROTTLE_ENABLED = TrueUse the@throttledecorator to enforce throttling rules on a view:from throttle.decorators import throttle

@throttle(zone='default')
def myview(request):
   ...Also works with class-based views:from django.views.generic import View
from django.utils.decorators import method_decorator

from throttle.decorators import throttle

class TestView(View):

    @method_decorator(throttle(zone='default'))
    def dispatch(self, *args, **kwargs):
        return super(TestView, self).dispatch(*args, **kwargs)

    def head(self, request):
        ...

    def get(self, request):
        ...Code:https://github.com/sobotklp/django-throttle-requestsDocumentation:https://readthedocs.org/projects/django-throttle-requests/
Package: django-thStorage
thStorage is a simple app to connect to th clusters’ storage systemdetail documentation is in the “docs” directoryQuick start1.Install based pubgins [django restframework;requests] like this:'pip install djangorestframework==3.11.0' 'pip install requests'2.Add “rest_framework” and “thStorage” to your INSTALLED_APPS setting like this:INSTALL_APPS = [ ... 'thStorage', 'rest_framework', ]3.Include the thStorage URLconf in your project urls.py like this:from thStorage import urls as thStorageUrls urlpatterns = [ path('admin/', admin.site.urls), path('login/', main.login), ] + thStorageUrls.urlpatterns4.Run python manage.py migrate to create thStorage models5.Run python manage.py collectstatic to migrate thStorage statics6.Set django project settings like:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } # restful api csrftoken!!!!!!

X_FRAME_OPTIONS = 'ALLOWALL' # (or your host name) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,"static").replace("\","/") TH_STORAGE_CONFIG = { 'TOKEN_UPDATE_IMTERVAL': 36000000, 'STORAGE_BACKEND_HOST':'thstorage backend server', 'STORAGE_BACKEND_APPID':'your thstorage appid', 'STORAGE_BACKEND_APPKEY':'your thstorage appkey', }7.Login thstorage when your project’s user login like this:from thStorage.models import THStorageUser ... systemUsername = user.username # systemUsername is tianhe system (in nscc-tj) username, and username is your project username cluster = "TH-HPC1" # cluster is tianhe system cluster name thStorageUser = THStorageUser(username,cluster,systemUsername) thStorageUser.Login()8.Set LocalStorage in login redirect page like this:from thStorage.thstorage import THStorageUser ... username = request.user.username systemUsername = request.session.get("systemUsername","") cluster = request.session.get("cluster","") thStorageUser = THStorageUser(username, cluster, systemUsername) t, u, c, s = thStorageUser.Login() thst = {"token": t, "username": s, "cluster": c,"platform":"default"} return render(request, 'index.html', {"thst":thst})

edit index.html

<script> var platform = "{{thst.platform}}"; var username = "{{thst.username}}"; var cluster = "{{thst.cluster}}"; var token = "{{thst.token}}"; localStorage.setItem("platform", platform); localStorage.setItem("username", username); localStorage.setItem("cluster", cluster); localStorage.setItem("token", token); </script>9.Add url “/thStorage” to your storage page by iframe:<body>
your html elements
<iframe id="myiframe" src="/thstorage" frameborder="0" width="100%" height="100%"></iframe>
</body> <script> var ifm= document.getElementById("myiframe"); //or set as your div element's height ifm.height=document.documentElement.clientHeight; </script>10.Add thStorage’s NetDiskUser to admin:from thStorage.models import NetDiskUserRegister your models here.
admin.site.register(NetDiskUser)12.Test thStorage:: Run python manage.py createsuperuser add a admin user add a test user to thStorage’s NetDiskUser by admin (user must map to real th systemuser)13.Start the development server and visithttp://127.0.0.1:8000/yourLoginUrlthen login and enjoy it!
Package: django-thumb
=====django-thumb=====django-thumb is a simple Django app contains 2 models fieldsto generate images from videos and write on imagesVisit the github repo https://github.com/AmrAnwar/django-thumb  for more info.Quick start-----------1. Add "thumb" to your INSTALLED_APPS setting like this::INSTALLED_APPS = [...'thumb',]2. Add the STATIC_ROOT, MEDIA_ROOT and MEDIA_URL in setting like:STATIC_ROOT = os.path.join(BASE_DIR, "static")MEDIA_ROOT = 'media'MEDIA_URL = '/media/'3. Add the MEDIA path to your urlpatterns in urls.py like:...from django.conf.urls.static import staticfrom django.conf import settingsurlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)3. Run `python manage.py collectstatic ` to create the static fields in your root.4. now you can use the app model fields like:from thumb import ImageThumbnailField, VideoThumbnailField5. in VideoThumbnailField you have to give the video field name if it's not named as `video`:my_video = models.FileField()thumb = VideoThumbnailField(video_field_name="my_video")6. test the Thumbnail Fields in the admin page http://127.0.0.1:8000/admin/### Visit https://github.com/AmrAnwar/django-thumb for more info.
Package: django-thumbnail-maker
Auto-generator of thumbnails for Django, using sorl-thumbnail.FeaturesAuto-genarates thumbnails using sorl-thumbnail while uploading (saving) imagesYou can use any engines & plugins you usually use with sorl-thumbnailThe application does not replace thumbnail templatetag and you can use everything you want from sorl-thumbnailCommand to auto-generate missing thumbnailsHow to UseGet the codeGet the code for the latest stable release use pip:$ pip install django-thumbnail-makerConfigure your projectRegister'thumbnail_maker', in theINSTALLED_APPSsection of
your project’s settings anywhere after'sorl.thumbnail'app (assume you already installedsorl-thumbnail):INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.sites',
    'django.contrib.comments',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.contenttypes',
    ...
    'sorl.thumbnail',
    ...
    'thumbnail_maker',
)Set up required thumb formats inTHUMBNAIL_MAKER_FORMATSdictionary.
Keys are the names for your formats (could be any string).
Values are tuples of length 2: first element is a geometry string (used insorl-thumbnail),
second is a dictionary with options (crop,quality,padding,format, etc.):THUMBNAIL_MAKER_FORMATS = {
    'banner':   ('400x300', {'crop': 'center',
                             'quality': 90}),
    '50x50':    ('50x50',   {}),
    'any_name': ('5x277',   {'padding': True})
}You can set upTHUMBNAIL_MAKER_DEBUGsetting.
By default it is set toFalsein order to pass exceptions
while saving models or while generating batch of thumbnails.
This setting is not required. Usage:THUMBNAIL_MAKER_DEBUG = TrueSet up your model’s fieldUseImageWithThumbnailsFieldandthumbsoption, wherethumbsis a tuple of thumb format names
(keys fromTHUMBNAIL_MAKER_FORMATSdictionary):from django.db import models
from thumbnail_maker.fields import ImageWithThumbnailsField

class Item(models.Model):
    image = ImageWithThumbnailsField(
        upload_to='somewhere',
        thumbs=('banner', '50x50'),
    )Templates usageAll of the examples assume that you first load thethumbnail_makertemplate tag in
your template:{% load thumbnail_maker %}A simple usage:{% usethumbnail item.image "banner" as im %}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endusethumbnail %}

{% usethumbnail item.image "50x50" as im %}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endusethumbnail %}You can also use string paths instead of image objects:{% usethumbnail "dummy/image.png" "50x50" as im %}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endusethumbnail %}Management commands usageDjango-thumbnail-maker comes with a manage.py command to generate missing thumbs.
You can use it while./manage.py make_thumbnails <app>.<model> <field>In case you want to make all thumbs replacing old ones, use--forceoption:./manage.py make_thumbnails --force <app>.<model> <field>
Package: django-thumborize
Minimal interface forthumborimaging service.FeaturesEasy thumbor URLsEasily build thumbor URLs with arguments and filters by calling simple functions.Default filtersSet default filters to be used on thumborized URLs.
These filters can be overridden by any calls that specify the same filters with different parameters.Flexible filters specificationFilters can be either a string delimited by:, alistordict. See usage for more.ChainingEasy, queryset like chaining for applying filters and resizing.For a full list of available filters, checkthumbor’s wiki.UsagefromthumborizeimportThumborURL# Filters as string.thumbor_url=ThumborURL("http://path/to/image.png",width=320,filters="quality(80):grayscale()")# Filters as list.thumbor_url=ThumborURL("http://path/to/image.png",width=320,filters=["quality(80)","grayscale()"])# Filters as dict.thumbor_url=ThumborURL("http://path/to/image.png",width=320,filters={"quality":"(80)","grayscale":"()",})thumbor_url.generate()'http://localhost:8888/JiuVg9d5Mry_kw4odvb5Zh1C_BY=/320x0/filters:quality(80):grayscale()/http://path/to/image.png'ChainingfromthumborizeimportThumborURLthumbor_url=ThumborURL("http://path/to/image.png")small_gray_image=thumbor_url.grayscale().resize(width=100,height=100)small_gray_image.generate()'http://localhost:8888/RFsfJakG9BsJUcbY2l1M6D5tthQ=/100x100/filters:grayscale()/http://path/to/image.png'low_quality_image=thumbor_url.quality(40).width(200)'http://localhost:8888/SB1ILIArmGzsd90-Mz-TxJVHwqI=/200x0/filters:quality(40)/http://path/to/image.png'# Original ThumborURL instance.thumbor_url.generate()'http://localhost:8888/O0Zqo6DMqqXHORdYncuspoaJlr0=/http://path/to/image.png'Shortcutimportthumborizethumborize.url("http://path/to/image.png",width=320,height=300)'http://localhost:8888/DYStA-Xwisc37dVz7bdXZ3u63QI=/320x300/http://path/to/image.png'Templates{% load thumborize %}<!-- Filters as string --><imgsrc="{% thumborize some_url width=320 filters='quality(80):grayscale()' %}"/><!-- Filters as a list object --><imgsrc="{% thumborize some_url width=320 filters=filter_list %}"/>InstallationInstall usingpip:$ pip install django-thumborizeIn order to usedjango-thumborizetemplatetags, you must add the app toINSTALLED_APPS:INSTALLED_APPS=(# Other django apps.."thumborize",# Any order is fine.)Configure basic thumbor settings:# Thumbor host URL.THUMBOR_SERVER="http://localhost:8888/"# This key must be the same used in thumbor# host to build safe URLs correctly.THUMBOR_SECURITY_KEY="MY_SECURE_KEY"# Default filters are optional.THUMBOR_DEFAULT_FILTERS={"quality":"(80)","grayscale":"()",}TestingInstallFirst clone the repository, then runmake installto install dev requirements.Run testsRunmake testto run tests.
Package: django-thumborstorage
A Django custom storage for Thumbor.Provides 2 custom storages classes:ThumborStorageandThumborMigrationStorage.UseThumborMigrationStorageon anImagefieldthat started with a classicFileSystemStorageyou want to upgrade to Thumbor without migrating your old
media. That way, Django continues to serve them from the file system until the
image is changed.Installpip install django-thumborstorageDependenciesPython 3.6+Django 2.1 to 3.2RequestsLibthumborRecommended:Django-thumbor(to manage thumbnails).ThumborUsagesettings.pyAdddjango_thumborstorageinINSTALLED_APPS.And set the following with your values:THUMBOR_SERVER='https://my.thumbor.server.com:8888'THUMBOR_SECURITY_KEY='MY_SECURE_KEY'# This may be a different host than THUMBOR_SERVER# only reachable by your Django server.THUMBOR_RW_SERVER='https://my.rw.thumbor.server.local:8888'models.pyJust set thestorageparameter in the ImageField you want to manage with Thumbor:fromdjango_thumborstorage.storagesimportThumborStorageclassStuff(models.Model):defupload_path(instance,filename):return'stuffs/%s'%filenamephoto=models.ImageField(upload_to=upload_path,storage=ThumborStorage(),height_field='photo_height',width_field='photo_width')photo_height=models.IntegerField(blank=True,null=True)photo_width=models.IntegerField(blank=True,null=True)In the codeYou can get the Thumboruuidfrom the<ImageField>instance using:my_stuff.photo.storage.key(my_stuff.photo.name)This is useful togenerate_url()withDjango-thumborwhen original files are stored on Thumbor. Thus,
you can pass the key as url parameter.CHANGELOG2.0.0Add support for Django 3.2.Possible breaking changeThe leading/in the path of the file stored in the database has been removed
due to a breaking change introduced un Django 3.2.11.https://docs.djangoproject.com/en/4.0/releases/3.2.11/#cve-2021-45452-potential-directory-traversal-via-storage-saveThat release handle seamlessly both pre-2.0.0 style (/image/…) and
post-2.0.0 style paths (image/…) so there is not need to migrate your database
to replace/image/…withimage/….1.13.0Drop support for Django < 2.1 and Python 2.7, 3.4 and 3.5Use GitHub actions for CI instead of Travis.1.11.0Drop support for Django < 1.11 and Python 3.4.Removemockfrom dependencies.0.92.2Fixreadonly_to_rw_url()to manage suffix in the urls.0.92.1Handle status code of the Thumbor server response when posting an image.0.92.0Added experimental Python 3.4 support (Thanks toCharlie 123.)Fixed broken support for Django < 1.7 (Thanks toRizziepit.)Added unicode support in file names (Thanks toRizziepit.)0.91.6Addstorages.readonly_to_rw_url(), a function to convert a read-only thumbor url in a rw url.0.91.5Use THUMBOR_SERVER to generate the original file url.Backward imcompatibilitiesTHUMBOR_SERVERandTHUMBOR_SECURITY_KEYare required in settings.0.91.4AddThumborStorage.key(name)to retrieve the Thumbor uuid from the name.0.91.3Backward imcompatibilitiesTHUMBOR_WRITABLE_SERVERsetting is replaced byTHUMBOR_RW_SERVERsince it is now used to retrieve the
original file.TODOPUT
Package: django-thumbs
The easiest way to create thumbnails for your images with Django. Works with any StorageBackend.FeaturesEasy to integrate in your code (no database changes, works as an ImageField)Works perfectly with any StorageBackendGenerates thumbnails after image is uploaded into memoryDeletes thumbnails when the image file is deletedProvides easy access to the thumbnails’ URLs (similar method as with ImageField)RequirementsPython 2.5+Django 1.1+PIL (Python Image Library)Getting ItYou can get Django-Thumbs by using pip or easy_install:$ pip install django-thumbs
or
$ easy_install django-thumbsIf you want to install it from source, grab the git repository from github and run setup.py:$ git clone git://github.com/skitoo/django-thumbs.git
$ cd django-thumbs
$ python setup.py installInstallationImport it in your models.py and replace ImageField with ImageWithThumbsField in your modelAdd a sizes attribute with a list of sizes you want to use for the thumbnailsMake sure your have defined MEDIA_URL in your settings.pyThat’s it!Working examplefrom django.db import models
from django_thumbs.db.models import ImageWithThumbsField

class Person(models.Model):
    photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(200,200)))
    second_photo = ImageWithThumbsField(upload_to='images')In this example we have a Person model with 2 image fields.You can see the field second_photo doesn’t have a sizes attribute. This field works exactly the same way as a normal ImageField.The field photo has a sizes attribute specifying desired sizes for the thumbnails. This field works the same way as ImageField but it also creates the desired thumbnails when uploading a new file and deletes the thumbnails when deleting the file.With ImageField you retrieve the URL for the image with: someone.photo.url With ImageWithThumbsField you retrieve it the same way. You also retrieve the URL for every thumbnail specifying its size: In this example we use someone.photo.url_125x125 and someone.photo.url_200x200 to get the URL of both thumbnails.UninstallAt any time you can go back and use ImageField again without altering the database or anything else. Just replace ImageWithThumbsField with ImageField again and make sure you delete the sizes attribute. Everything will work the same way it worked before using django-thumbs. Just remember to delete generated thumbnails in the case you don’t want to have them anymore.