本文整理汇总了Python中swapper.load_model函数的典型用法代码示例。如果您正苦于以下问题:Python load_model函数的具体用法?Python load_model怎么用?Python load_model使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load_model函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup_imagestore_permissions
def setup_imagestore_permissions(instance, created, **kwargs):
if not created:
return
try:
Album = swapper.load_model('imagestore', 'Album')
Image = swapper.load_model('imagestore', 'Image')
image_applabel, image_classname = Image._meta.app_label, Image.__name__.lower()
album_applabel, album_classname = Album._meta.app_label, Album.__name__.lower()
image_ctype = ContentType.objects.get(app_label=image_applabel, model=image_classname)
album_ctype = ContentType.objects.get(app_label=album_applabel, model=album_classname)
add_image_permission = Permission.objects.get(codename='add_%s' % image_classname, content_type=image_ctype)
add_album_permission = Permission.objects.get(codename='add_%s' % album_classname, content_type=album_ctype)
change_image_permission = Permission.objects.get(codename='change_%s' % image_classname, content_type=image_ctype)
change_album_permission = Permission.objects.get(codename='change_%s' % album_classname, content_type=album_ctype)
delete_image_permission = Permission.objects.get(codename='delete_%s' % image_classname, content_type=image_ctype)
delete_album_permission = Permission.objects.get(codename='delete_%s' % album_classname, content_type=album_ctype)
instance.user_permissions.add(add_image_permission, add_album_permission,)
instance.user_permissions.add(change_image_permission, change_album_permission,)
instance.user_permissions.add(delete_image_permission, delete_album_permission,)
except ObjectDoesNotExist:
# Permissions are not yet installed or content does not created yet
# probaly this is first
pass
示例2: process_zipfile
def process_zipfile(uploaded_album):
Image = swapper.load_model('imagestore', 'Image')
Album = swapper.load_model('imagestore', 'Album')
if default_storage.exists(uploaded_album.zip_file.name):
# TODO: implement try-except here
zip = zipfile.ZipFile(uploaded_album.zip_file)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
if not uploaded_album.album:
uploaded_album.album = \
Album.objects.create(name=uploaded_album.new_album_name)
for filename in sorted(zip.namelist()):
try:
encoding = chardet.detect(filename)['encoding']
unicode_filename = filename.decode(encoding)
except ValueError: # if detect takes unicode string
unicode_filename = filename
# do not process meta files
if unicode_filename.startswith('__'):
continue
logger.info('Processing file {}.'.format(unicode_filename))
data = zip.read(filename)
if len(data):
try:
# the following is taken from django.forms.fields.ImageField:
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
# verify() must be called immediately after the constructor.
PILImage.open(BytesIO(data)).verify()
except Exception as e:
# if a "bad" file is found we just skip it.
logger.info('Error verify image: %s' % e)
continue
if hasattr(data, 'seek') and \
isinstance(data.seek, collections.Callable):
logger.info('Seeked')
data.seek(0)
try:
img = Image(album=uploaded_album.album)
img.image.save(filename, ContentFile(data))
img.save()
except Exception as e:
logger.info('Error create Image: %s' % e)
continue
zip.close()
uploaded_album.delete()
示例3: test_create
def test_create(self):
Type = swapper.load_model('default_app', 'Type')
Item = swapper.load_model('default_app', 'Item')
Item.objects.create(
type=Type.objects.create(name="Type 1"),
name="Item 1",
)
self.assertEqual(Item.objects.count(), 1)
item = Item.objects.all()[0]
self.assertEqual(item.type.name, "Type 1")
示例4: set_for_events
def set_for_events(self, delete=True, **event_filter):
"""
Update EventResult cache for the given events. The event query should
be specified as query keyword arguments, rather than a queryset, so
that a JOIN can be used instead of retrieving the results for each
event separately.
"""
# Delete existing EventResults (using denormalized Event fields)
if delete:
er_filter = {
'event_' + key: val for key, val in event_filter.items()
}
self.filter(**er_filter).delete()
# Filter results (using JOIN through Report to Event)
Result = swapper.load_model('vera', 'Result')
result_filter = {
'report__event__' + key: val for key, val in event_filter.items()
}
ers = []
results = Result.objects.valid_results(
**result_filter
).select_related('report__event')
for result in results:
er = self.model(
event=result.report.event,
result=result
)
er.denormalize()
ers.append(er)
self.bulk_create(ers)
示例5: test_swap_fields
def test_swap_fields(self):
Type = swapper.load_model('default_app', 'Type')
fields = dict(
(field.name, field)
for field in Type._meta.fields
)
self.assertIn('code', fields)
示例6: test_fields
def test_fields(self):
Type = swapper.load_model('default_app', 'Type')
fields = {
field.name: field
for field in Type._meta.fields
}
self.assertIn('name', fields)
示例7: test_page_fails_with_nonexistant_template
def test_page_fails_with_nonexistant_template(client):
Page = swapper.load_model('varlet', 'Page')
homepage = Page(url='', template='home.html')
with pytest.raises(ValidationError) as e:
homepage.full_clean()
homepage.save()
with pytest.raises(TemplateDoesNotExist):
client.get(homepage.get_absolute_url())
示例8: process_tweet_queue
def process_tweet_queue(self):
"""
Inserts any queued tweets into the database.
It is ok for this to be called on a thread other than the streaming thread.
"""
# this is for calculating the tps rate
now = time.time()
diff = now - self.time
self.time = now
try:
batch = self.queue.get_all_nowait()
except Queue.Empty:
return 0
if len(batch) == 0:
return 0
Tweet = load_model("twitter_stream", "Tweet")
tweets = []
for status in batch:
if settings.CAPTURE_EMBEDDED and 'retweeted_status' in status:
if self.to_file:
tweets.append(json.dumps(status['retweeted_status']))
else:
tweets.append(Tweet.create_from_json(status['retweeted_status']))
if self.to_file:
if 'retweeted_status' in status:
del status['retweeted_status']
tweets.append(json.dumps(status))
else:
tweets.append(Tweet.create_from_json(status))
if tweets:
if self.to_file:
if not self._output_file or self._output_file.closed:
self._output_file = open(self.to_file, 'ab')
self._output_file.write("\n".join(tweets) + "\n")
self._output_file.flush()
logger.info("Dumped %s tweets at %s tps to %s" % (len(tweets), len(tweets) / diff, self.to_file))
else:
Tweet.objects.bulk_create(tweets, settings.INSERT_BATCH_SIZE)
logger.info("Inserted %s tweets at %s tps" % (len(tweets), len(tweets) / diff))
else:
logger.info("Saved 0 tweets")
if settings.DEBUG:
# Prevent apparent memory leaks
# https://docs.djangoproject.com/en/dev/faq/models/#why-is-django-leaking-memory
from django import db
db.reset_queries()
return len(tweets) / diff
示例9: test_page_renders_html_ok
def test_page_renders_html_ok(client):
Page = swapper.load_model('varlet', 'Page')
homepage = Page(url='', template='varlet/pages/layouts/test_template.html')
homepage.full_clean()
homepage.save()
response = client.get(homepage.get_absolute_url())
assert response.status_code == 200
response.render()
assert '<b>Test template</b>' in force_text(response.content)
示例10: test_page_renders_json_detailview_ok
def test_page_renders_json_detailview_ok(client):
Page = swapper.load_model('varlet', 'Page')
page = Page(url='/test/', template='varlet/pages/layouts/test_template.html')
page.full_clean()
page.save()
response = client.get(page.get_absolute_url(), HTTP_ACCEPT="application/json")
assert response.status_code == 200
data = json.loads(force_text(response.content))
assert data['get_absolute_url'] == '/test/'
示例11: test_rendering_sitemaps
def test_rendering_sitemaps(rf):
Page = swapper.load_model('varlet', 'Page')
pages = [Page.objects.create(url=str(x), template="varlet/pages/layouts/test_template.html") for x in range(1, 5)]
sm = PageSitemap()
response = sitemap(rf.get('/'), sitemaps={'pages': sm})
response.render()
assert '<loc>http://example.com/3/</loc>' in force_text(response.content)
assert '<loc>http://example.com/2/</loc>' in force_text(response.content)
assert '<loc>http://example.com/1/</loc>' in force_text(response.content)
示例12: get_admin_url
def get_admin_url(self):
model = swapper.load_model('varlet', 'Page')
if not admin.site.is_registered(model):
return None
try:
url = reverse('admin:{}_{}_autocomplete'.format(
model._meta.app_label, model._meta.model_name))
except NoReverseMatch:
return None
return url
示例13: get_page
def get_page(path):
Page = swapper.load_model('varlet', 'Page')
field = Page._meta.get_field('url')
try:
cleaned_path = field.to_python(path)
except ValidationError:
return None
try:
return Page.objects.get(url=cleaned_path)
except (Page.DoesNotExist, MultipleObjectsReturned):
return None
示例14: process_zipfile
def process_zipfile(uploaded_album):
Image = swapper.load_model('imagestore', 'Image')
Album = swapper.load_model('imagestore', 'Album')
if default_storage.exists(uploaded_album.zip_file.name):
# TODO: implement try-except here
zip = zipfile.ZipFile(uploaded_album.zip_file)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
if not uploaded_album.album:
uploaded_album.album = Album.objects.create(name=uploaded_album.new_album_name)
for filename in sorted(zip.namelist()):
if filename.startswith('__'): # do not process meta files
continue
print(filename.encode('ascii', errors='replace'))
data = zip.read(filename)
if len(data):
try:
# the following is taken from django.forms.fields.ImageField:
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
# verify() must be called immediately after the constructor.
PILImage.open(six.moves.cStringIO(data)).verify()
except Exception as ex:
# if a "bad" file is found we just skip it.
print('Error verify image: %s' % ex.message)
continue
if hasattr(data, 'seek') and isinstance(data.seek, collections.Callable):
print('seeked')
data.seek(0)
try:
img = Image(album=uploaded_album.album)
img.image.save(filename, ContentFile(data))
img.save()
except Exception as ex:
print('error create Image: %s' % ex.message)
zip.close()
uploaded_album.delete()
示例15: setup_imagestore_permissions
def setup_imagestore_permissions(instance, created, **kwargs):
if not created:
return
try:
Album = swapper.load_model('imagestore', 'Album')
Image = swapper.load_model('imagestore', 'Image')
perms = []
for model_class in [Album, Image]:
for perm_name in ['add', 'change', 'delete']:
app_label, model_name = model_class._meta.app_label, model_class.__name__.lower()
perm = Permission.objects.get_by_natural_key('%s_%s' % (perm_name, model_name), app_label, model_name)
perms.append(perm)
instance.user_permissions.add(*perms)
except ObjectDoesNotExist:
# Permissions are not yet installed or content does not created yet
# probaly this is first
pass