本文整理汇总了Python中models.Image.image方法的典型用法代码示例。如果您正苦于以下问题:Python Image.image方法的具体用法?Python Image.image怎么用?Python Image.image使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Image
的用法示例。
在下文中一共展示了Image.image方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: receive
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def receive():
data = request.data
data = xmltodict.parse(data)['xml']
if data['MsgType'] == 'text':
return send_text(data['FromUserName'], 'hi')
if data['MsgType'] == 'image':
token = current_access_token()
file_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s' % (token, data['MediaId'])
file = requests.get(file_url, stream=True).raw
i = Image()
i.image = file
uuid = shortuuid.ShortUUID().random(length=6)
while Image.objects(iid=uuid):
uuid = shortuuid.ShortUUID().random(length=6)
i.iid = uuid
i.title = data['MediaId']
i.user = system_user
i.description = ''
i.tags = []
i.save()
return send_text(
data['FromUserName'], '업로드 성공, 사진주소:%s%s' % (
request.url_root[:-1], url_for('light-cms.image', iid=i.iid)
)
)
示例2: post
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def post(self):
"Upload via a multitype POST message"
img = self.request.get("img")
# if we don't have image data we'll quit now
if not img:
self.redirect("/")
return
try:
width = int(self.request.get("width"))
hight = int(self.request.get("height"))
except ValueError:
image_content = img
else:
image_content = images.resize(img, width, height)
original_content = img
thumb_content = images.resize(img, 100, 100)
image = Image()
image.image = db.Blob(image_content)
image.original = db.Blob(original_content)
image.thumb = db.Blob(thumb_content)
image.user = users.get_current_user()
image.put()
self.redirect("/")
示例3: upload
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def upload():
with open('data.csv') as f:
reader = csv.DictReader(f)
for row in reader:
try:
s = Store()
print row['name'], row['images'], row['types']
if re.search("\[.*\]", row['reference']):
row['place_id'] = row['scope']
row['scope'] = row['latlng']
row['latlng'] = row['address']
row['address'] = row['photos']
row['photos'] = row['reference']
print row['name'], row['images'], row['types']
s.tags = json.loads(row['types'])
s.point = db.GeoPt(*eval(row['latlng']))
s.reference = row['reference'] and row['reference'][0] or ""
s.address = row['address']
s.name = row['name']
for img in eval(row['images']):
image = Image()
image.image = img
image.put()
s.imgs.append(image)
except Exception as e:
pass
finally:
s.put()
示例4: post
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def post(self):
"Upload via a multitype POST message"
if self.request.get('img'):
try:
# check we have numerical width and height values
width = int(self.request.get("width"))
height = int(self.request.get("height"))
except ValueError:
# if we don't have valid width and height values
# then just use the original image
image_content = google.appengine.api.images.resize(self.request.get("img"),
IMAGE_WIDTH, IMAGE_HEIGHT)
thumb_content = google.appengine.api.images.resize(self.request.get("img"), 100, 100)
else:
# if we have valid width and height values
# then resize according to those values
image_content = google.appengine.api.images.resize(self.request.get("img"), width, height)
# always generate a thumbnail for use on the admin page
thumb_content = google.appengine.api.images.resize(self.request.get("img"), 100, 100)
else:
image_content = None
if not self.request.get('key'):
logging.critical('No key and no image! Cannot save image.')
return self.redirect('/admin')
# check if image is being edited
if self.request.get('key'):
image = db.get(self.request.get("key"))
if self.request.get('position'):
import datetime
position = int(self.request.get('position'))
images = imageQuery().fetch(100)
offset_image = images.pop(position- 1)
if position == 1:
time_offset = -datetime.timedelta(milliseconds=10)
else:
time_offset = datetime.timedelta(milliseconds=10)
if not offset_image.key() == image.key():
image.date = offset_image.date + time_offset
else:
# create the image object
image = Image()
image.user = users.get_current_user()
image.title = self.request.get('title')
if image_content:
# and set the properties to the relevant values
image.image = db.Blob(image_content)
# we always store the original here in case of errors
# although it's currently not exposed via the frontend
image.thumb = db.Blob(thumb_content)
# store the image in the datasore
image.put()
# and redirect back to the admin page
self.redirect('/admin')
示例5: post
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def post(self):
"Upload via a multitype POST message"
try:
# check we have numerical width and height values
width = int(self.request.get("width"))
height = int(self.request.get("height"))
except ValueError:
# if we don't have valid width and height values
# then just use the original image
image_content = self.request.get("img")
else:
# if we have valid width and height values
# then resize according to those values
image_content = images.resize(self.request.get("img"), width, height)
# get the image data from the form
original_content = self.request.get("img")
# always generate a thumbnail for use on the admin page
thumb_content = images.resize(self.request.get("img"), 100, 100)
# create the image object
image = Image()
# Try and create an s3 connection
if len(awskeys.AWS_ACCESS_KEY_ID) > 0 and len(awskeys.AWS_SECRET_ACCESS_KEY) > 0:
s3 = GoogleS3.AWSAuthConnection(awskeys.AWS_ACCESS_KEY_ID, awskeys.AWS_SECRET_ACCESS_KEY)
else:
s3 = None
# and set the properties to the relevant values
image.image = db.Blob(image_content)
image.user = users.get_current_user()
if s3 is None:
# we always store the original here in case of errors
# although it's currently not exposed via the frontend
image.original = db.Blob(original_content)
image.thumb = db.Blob(thumb_content)
# store the image in the datasore
image.put()
else:
# we want to store in S3, so store the data and use the key
image.put()
# Put the 3 different images
s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_original",original_content)
s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_thumb",thumb_content)
s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_image",image_content)
# and redirect back to the admin page
self.redirect('/')
示例6: multiuploader
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def multiuploader(request):
if request.method == 'POST':
log.info('received POST to main multiuploader view')
if request.FILES == None:
return HttpResponseBadRequest('Must have files attached!')
#getting file data for farther manipulations
file = request.FILES[u'files[]']
wrapped_file = UploadedFile(file)
filename = wrapped_file.name
file_size = wrapped_file.file.size
log.info ('Got file: "'+str(filename)+'"')
#writing file manually into model
#because we don't need form of any type.
image = Image()
image.title=str(filename)
image.image=file
image.save()
log.info('File saving done')
#getting url for photo deletion
file_delete_url = '/delete/'
#getting file url here
file_url = '/'
#getting thumbnail url using sorl-thumbnail
im = get_thumbnail(image, "80x80", quality=50)
thumb_url = im.url
#generating json response array
result = []
result.append({"name":filename,
"size":file_size,
"url":file_url,
"thumbnail_url":thumb_url,
"delete_url":file_delete_url+str(image.pk)+'/',
"delete_type":"POST",})
response_data = simplejson.dumps(result)
return HttpResponse(response_data, mimetype='application/json')
else: #GET
return render_to_response('multiuploader_main.html',
{'static_url':settings.MEDIA_URL,
'open_tv':u'{{',
'close_tv':u'}}'},
)
示例7: drop
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def drop():
file = request.files['file']
i = Image()
i.title = file.filename
i.image = file
uuid = shortuuid.ShortUUID().random(length=6)
while Image.objects(iid=uuid):
uuid = shortuuid.ShortUUID().random(length=6)
i.iid = uuid
if login.current_user.is_active():
i.user = login.current_user._get_current_object()
else:
i.user = system_user
i.description = ''
i.tags = []
i.save()
return jsonify(id=uuid)
示例8: post
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def post(self):
"Upload via a multitype POST message"
img = self.request.get("img")
# if we don't have image data we'll quit now
if not img:
self.redirect('/')
return
# we have image data
try:
# check we have numerical width and height values
width = int(self.request.get("width"))
height = int(self.request.get("height"))
except ValueError:
# if we don't have valid width and height values
# then just use the original image
image_content = img
else:
# if we have valid width and height values
# then resize according to those values
image_content = images.resize(img, width, height)
# get the image data from the form
original_content = img
# always generate a thumbnail for use on the admin page
thumb_content = images.resize(img, 100, 100)
# create the image object
image = Image()
# and set the properties to the relevant values
image.image = db.Blob(image_content)
# we always store the original here in case of errors
# although it's currently not exposed via the frontend
image.original = db.Blob(original_content)
image.thumb = db.Blob(thumb_content)
image.user = users.get_current_user()
# store the image in the datasore
image.put()
# and redirect back to the admin page
self.redirect('/')
示例9: gallery_drop
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def gallery_drop(gid):
if not login.current_user.is_active():
flash('앨범기능엔 로그인이 필요합니다')
return redirect(url_for('light-cms.user_login'))
g = Gallery.objects.get_or_404(gid=gid)
file = request.files['file']
i = Image()
i.gallery.append(g)
i.title = file.filename
i.image = file
uuid = shortuuid.ShortUUID().random(length=6)
while Image.objects(iid=uuid):
uuid = shortuuid.ShortUUID().random(length=6)
i.iid = uuid
i.user = login.current_user._get_current_object()
i.description = ''
i.tags = []
i.save()
return jsonify(id=uuid)
示例10: post
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def post(self, key):
checkkey = UploadRequestKeys.get(key)
if not checkkey:
self.error(404)
if checkkey.expire_date < datetime.now():
self.error(404)
img = self.request.get("img")
# if we don't have image data we'll quit now
if not img:
return None
try:
width = int(self.request.get("width"))
hight = int(self.request.get("height"))
except ValueError:
image_content = img
else:
image_content = images.resize(img, width, height)
original_content = img
thumb_content = images.resize(img, 100, 100)
image = Image()
image.image = db.Blob(image_content)
image.original = db.Blob(original_content)
image.thumb = db.Blob(thumb_content)
image.user = users.get_current_user()
image.realm = RealmKeys.get(checkkey.realm_key)
image.put()
checkkey.delete()
# self.response.out.write(simplejson.dumps({'img_url'::}))
context = {
"image": True,
"img_url": "http://org-images.appspot.com/i/img?id=%s" % image.key(),
"thumb_url": "http://org-images.appspot.com/i/thumb?id=%s" % image.key(),
}
path = os.path.join(os.path.dirname(__file__), "templates", "show_links.html")
# render the template with the provided context
self.response.out.write(template.render(path, context))
示例11: upload_image
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def upload_image(request):
"""
Handles image uploads and assigns them to the correct user. Resizes the image before uploading.
The uploaded image's URL is in the HTTP header (Location)
"""
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
img = Image()
img.user = request.user
img.note_id = form.cleaned_data['note']
img.image = form.cleaned_data['image']
img.save()
# Build a response
response = HttpResponse(status=201)
response['Location'] = img.image.url.replace(settings.AWS_MEDIA_URL,settings.MEDIA_URL,1)
return response
else:
return HttpResponse(status=400)
return HttpResponseForbidden()
示例12: query_image
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def query_image(exp):
# Build a service object for interacting with the API. Visit
# the Google APIs Console <http://code.google.com/apis/console>
# to get an API key for your own application.
service = build("customsearch", "v1",
developerKey="AIzaSyCDlCGXWMJa4JPsbT1r0gJQPbCMo-RpwE4")
# https://developers.google.com/custom-search/json-api/v1/reference/cse/list
res = service.cse().list(
q=exp,
cx='008947772147471846402:fdhywbjbitw',
num=4,
searchType="image",
imgColorType='color',
imgType='photo',
safe='high',
rights='cc_publicdomain',
filter='1'
).execute()
parsed_res = json.dumps(res)
json_res = json.loads(parsed_res)
items = []
for i in range(4):
img_url = json_res['items'][i]['link']
img = Image()
f = ""
try:
f = urllib2.urlopen(img_url).read() # Opens the url as an image file so we can store it!
except urllib2.HTTPError, e:
print "There was an http error with url: "+img_url
print e
# TODO: Figure out how to best preserve quality while resizing
if f:
op_img = images.Image(f)
op_img.resize(width=256, height=256, crop_to_fit=False)
small_img = op_img.execute_transforms(output_encoding=images.JPEG)
img.image = small_img
img_id = img.put()
items.append(ImageMessage(image_url="getgimage?id="+img_id.urlsafe()))
示例13: post
# 需要导入模块: from models import Image [as 别名]
# 或者: from models.Image import image [as 别名]
def post(self):
# Grab album from url
urlstring = self.request.POST['album']
album_key = ndb.Key(urlsafe=urlstring)
album = album_key.get()
# Check whether we're storing a album or a Question
if self.request.GET['album'] == '1':
album.title = self.request.POST['albumTitle']
album.category = self.request.POST['categoryTitle']
album.put()
time.sleep(0.1)
# Save album and redirect to edit if the user clicks on 'Save and continue editing'
# Else, save album and go back to the main page which lists all albums
if self.request.POST.get('stay') == '1':
self.redirect('/edit?album=1&id='+urlstring)
else:
if album.album_type == 'match':
self.redirect('/match')
elif album.album_type == 'correlate':
self.redirect('/correlate')
else:
self.redirect('/oddmanout')
else:
# Create Question with the album as parent for strong consistency
question = ""
new = "1"
if self.request.POST['question'] == "":
question = Question(parent=album_key)
question.question_id = question.put().id()
else:
new = "0"
question_url = self.request.POST['question']
question_key = ndb.Key(urlsafe=question_url)
question = question_key.get()
question.title = self.request.get('title')
question.fact = self.request.get('fact')
question.effect = self.request.get('revealEffect')
question.difficulty = self.request.get('difficulty')
# Create answer choices
answer = int(self.request.get('correct_answer'))
input_images = self.request.get('image', allow_multiple=True)
num_images = 4
if album.album_type == 'correlate':
num_images = 5
image_list = []
for i in range(num_images):
img = ""
input_img = input_images[i]
# If old retrieve the Image
if new == "0":
img = question.images[i]
else:
img = Image()
# Resize image
if input_img:
op_img = images.Image(input_img)
op_img.resize(width=256, height=256, crop_to_fit=True)
result_img = op_img.execute_transforms(output_encoding=images.JPEG)
img.image = result_img
# Set the title and correct fields
if answer == i:
img.title = "correct_answer_"+str(i)
img.correct = True
elif num_images == 5 and i == 0: # This is if the album is of type Correlate
img.title = "main_image_"+str(i)
img.correct = False
else:
img.title = "incorrect_answer_"+str(i)
img.correct = False
# If old Question, free up the old Image and put in new Image
if new == "0":
question.images.pop(i)
question.images.insert(i, img)
else:
question.images.append(img)
question.put()
# Query all Question(s) for the album in recently added order for /create
# Retrieve previously input values, and indicate whether this is a new album (edit)
questions = Question.query(ancestor=album_key).order(-Question.date).fetch()
retrieve = 1
edit = self.request.GET['edit']
template_values = {
'album': album,
'album_type': album.album_type,
'questions': questions,
'edit': edit,
'retrieve': retrieve
}
template = JINJA_ENVIRONMENT.get_template('create.html')
self.response.write(template.render(template_values))