def test_document_version_download_user_view(self): self.login( username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD ) self.assertEqual(Document.objects.count(), 1) response = self.post( 'documents:document_version_download', args=( self.document.latest_version.pk, ) ) self.assertEqual(response.status_code, 302) self.role.permissions.add( permission_document_download.stored_permission ) response = self.post( 'documents:document_version_download', args=( self.document.latest_version.pk, ) ) self.assertEqual(response.status_code, 200) buf = BytesIO() buf.write(response.content) self.assertEqual( HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM ) del(buf)
def test_logslice_api(test_repository, webapp, activate_responses, logname, line_range, gzipped, num_loads): job = Job.objects.create(repository=test_repository, guid="12345", project_specific_id=1) fake_log_url = 'http://www.fakelog.com/log.gz' JobLog.objects.create(job=job, name=logname, url=fake_log_url, status=JobLog.PARSED) lines = ['cheezburger %s' % i for i in range(10)] # set up a file response text = "\n".join(lines) + '\n' content = BytesIO() if gzipped: with gzip.GzipFile('none', 'w', fileobj=content) as gz: gz.write(text) else: content.write(text) content.seek(0) responses.add(responses.GET, fake_log_url, body=content.read(), content_type="text/plain;charset=utf-8", status=200) # now test it for i in range(num_loads): resp = webapp.get(reverse('logslice-list', kwargs={"project": test_repository.name}) + '?start_line={}&end_line={}&job_id=1'.format(line_range[0], line_range[1])) assert resp.json == [{'index': i + line_range[0], 'text': l + '\n'} for (i, l) in enumerate(lines[line_range[0]:line_range[1]])]
def test_document_version_download_user_view(self): # TODO: Skip this test's file descriptor check until it gets migrate # SingleObjectDownloadView CBV self.login(username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD) self.assertEqual(Document.objects.count(), 1) response = self.post('documents:document_version_download', args=(self.document.latest_version.pk, )) self.assertEqual(response.status_code, 302) self.role.permissions.add( permission_document_download.stored_permission) # Set the expected_content_type for common.tests.mixins.ContentTypeCheckMixin self.expected_content_type = self.document.file_mimetype response = self.post('documents:document_version_download', args=(self.document.latest_version.pk, )) self.assertEqual(response.status_code, 200) buf = BytesIO() buf.write(response.content) self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM) del (buf)
def test_document_multiple_download_user_view(self): # TODO: Skip this test's file descriptor check until it gets migrate # SingleObjectDownloadView CBV self.login(username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD) self.assertEqual(Document.objects.count(), 1) response = self.post('documents:document_multiple_download', data={'id_list': self.document.pk}) self.assertEqual(response.status_code, 302) self.role.permissions.add( permission_document_download.stored_permission) response = self.post('documents:document_multiple_download', data={'id_list': self.document.pk}) self.assertEqual(response.status_code, 200) buf = BytesIO() buf.write(response.content) self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM) del (buf)
def test_document_version_download_user_view(self): self.login(username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD) self.assertEqual(Document.objects.count(), 1) response = self.post('documents:document_version_download', args=(self.document.latest_version.pk, )) self.assertEqual(response.status_code, 302) self.role.permissions.add( permission_document_download.stored_permission) response = self.post('documents:document_version_download', args=(self.document.latest_version.pk, )) self.assertEqual(response.status_code, 200) buf = BytesIO() buf.write(response.content) self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM) del (buf)
def post(self, request): src = request.body.decode('utf-8') # 检测用户上传文件是否为图片 if src[9:14] != 'image': return JsonResponse({"msg": "fail"}) # 定位文件所包含base64编码信息的位置并进行解码转换存入内存文件 res = src.find('base64,') result_src = src[res + len('base64,'):] f = BytesIO() data = base64.b64decode(result_src) f.write(data) img = InMemoryUploadedFile(f, None, "image", len(data), None, None) # 将文件上传至云服务器 leancloud.init('tiM1T9UGqwf6QTyXkn9kcL9z-gzGzoHsz', '1GzzyA6uv4l8JNGd6etu5V5o') execute = leancloud.File('image', img) execute.save() result_qrcode = qrcode.make(execute.url) buf = BytesIO() result_qrcode.save(buf) img_stream = buf.getvalue() result_img = base64.b64encode(img_stream) return JsonResponse({ "msg": "success", "image": bytes.decode(result_img, 'utf-8') })
def open(self, mode=None): try: image = BytesIO() image.write(urlopen(self.path).read()) image.seek(0) yield image except URLError as e: logger.exception('Error image urlopen') raise HttpError(e)
def generate(source_file, storage, prefix=None, replace=False, fill=None): """ Creates favicons from a source file and upload into storage. This also create the ieconfig.xml file. :param source_file: File to use as string (local path) or filelike object :type source_file: str or file :param storage: Storage where upload files :type storage: :class:`django.core.files.storage.Storage` :param prefix: Prefix included in new files' names :type prefix: str :param replace: Delete file is already existing. :type replace: bool :param fill: Background color for generated precomposed-* icons :type fill: tuple of length 3, as returned by PIL.ImageColor.getrgb(color) """ prefix = prefix or '' def write_file(output_file, name, replace=False): """Upload to storage.""" name = prefix + name if storage.exists(name): if replace: storage.delete(name) else: return content = File(output_file, name) storage._save(name, content) def save_png(img, output_name, size): img.thumbnail(size=size, resample=Image.ANTIALIAS) output_file = BytesIO() img.save(output_file, format='PNG') write_file(output_file, output_name) # Save ICO img = Image.open(source_file) output_file = BytesIO() img.save(fp=output_file, format='ICO', sizes=ICO_SIZES) write_file(output_file, 'favicon.ico') # Save PNG for size in PNG_SIZES: img = Image.open(source_file) save_png(img, 'favicon-%s.png' % size, (size, size)) for size, output_name in WINDOWS_PNG_SIZES: img = Image.open(source_file) save_png(img, output_name, size) for size in FILLED_SIZES: img = alpha_to_color(Image.open(source_file), fill) save_png(img, 'favicon-precomposed-%s.png' % size, (size, size)) # Create ieconfig.xml output_name = 'ieconfig.xml' output_file = StringIO() template = get_template('favicon/ieconfig.xml') output_content = template.render({'tile_color': 'FFFFFF'}) output_file.write(output_content) write_file(output_file, 'ieconfig.xml')
def test_printing(one_per_page): from lippukala.printing import OrderPrinter printer = OrderPrinter() printer.ONE_TICKET_PER_PAGE = one_per_page for x in xrange(3): order = _create_test_order() printer.process_order(order) outf = BytesIO() outf.write(printer.finish()) assert outf.getvalue().startswith(b"%PDF")
def test_document_version_download(self): with open(TEST_SMALL_DOCUMENT_PATH) as file_object: document = self.document_type.new_document(file_object=File(file_object)) response = self.client.get(reverse("rest_api:documentversion-download", args=(document.latest_version.pk,))) buf = BytesIO() buf.write(response.content) self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM) del (buf)
def build_xlsx_response(wb, title="report"): title = generate_filename(title, '.xlsx') myfile = BytesIO() myfile.write(save_virtual_workbook(wb)) response = HttpResponse( myfile.getvalue(), content_type= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % title response['Content-Length'] = myfile.tell() return response
def save_result(base64Str, player, name, game_secret, inviter): imgdata = base64.b64decode(base64Str[22:]+'==') file = BytesIO() file.write(imgdata) img = InMemoryUploadedFile(file, None, 'result.jpg', None, len(imgdata), None, None) result = Result.objects.filter(player=player,name=name, game_secret=game_secret, inviter=inviter).first() if not result: Result.objects.create(img=img,player=player, name=name, game_secret=game_secret, inviter=inviter) else: result.img = img result.save()
def user_login(request): full_path = request.get_full_path() if 'code' in full_path: code = request.GET.get('code') user_data = wechat_api(code) nickname = user_data['nickname'] union_id = user_data['union_id'] head_img = user_data['head_img'] user = User.objects.filter(union_id=union_id).first() status = request.GET.get('status') if user: if user.name and user.hotel_name: return redirect('/customer_profile/{0}/'.format(user.id)) else: return redirect('/customer/save_message/') else: event = Event.objects.all().first() user = User.objects.create(union_id=union_id, head_img=head_img, status=0, event=event) request.session['uid'] = user.id qr = qrcode.make( 'https://pinkslash.metatype.cn/wechat_login/?status=sendcredits_{0}_{1}' .format(user.id, event.id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='user.png', content_type='image/png', size=len(qr_data), charset=None) _user = User.objects.get(id=user.id) _user.qrcode = qr_img _user.save() return redirect('/customer/save_message/') else: redirect_uri = 'https://pinkslash.metatype.cn' + full_path get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7594d7d49e0235f&redirect_uri=" + \ redirect_uri + "&response_type=code&scope=snsapi_userinfo" return redirect(get_code_url) return HttpResponse("xixi")
def test_document_download(self): with open(TEST_SMALL_DOCUMENT_PATH) as file_object: document = self.document_type.new_document( file_object=file_object, ) response = self.client.get( reverse('rest_api:document-download', args=(document.pk, ))) buf = BytesIO() buf.write(response.content) self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM) del (buf)
def test_strips_underscore_headers(self): """WSGIRequestHandler ignores headers containing underscores. This follows the lead of nginx and Apache 2.4, and is to avoid ambiguity between dashes and underscores in mapping to WSGI environ, which can have security implications. """ def test_app(environ, start_response): """A WSGI app that just reflects its HTTP environ.""" start_response('200 OK', []) http_environ_items = sorted( '%s:%s' % (k, v) for k, v in environ.items() if k.startswith('HTTP_') ) yield (','.join(http_environ_items)).encode('utf-8') rfile = BytesIO() rfile.write(b"GET / HTTP/1.0\r\n") rfile.write(b"Some-Header: good\r\n") rfile.write(b"Some_Header: bad\r\n") rfile.write(b"Other_Header: bad\r\n") rfile.seek(0) # WSGIRequestHandler closes the output file; we need to make this a # no-op so we can still read its contents. class UnclosableBytesIO(BytesIO): def close(self): pass wfile = UnclosableBytesIO() def makefile(mode, *a, **kw): if mode == 'rb': return rfile elif mode == 'wb': return wfile request = Stub(makefile=makefile) server = Stub(base_environ={}, get_app=lambda: test_app) # We don't need to check stderr, but we don't want it in test output old_stderr = sys.stderr sys.stderr = StringIO() try: # instantiating a handler runs the request as side effect WSGIRequestHandler(request, '192.168.0.2', server) finally: sys.stderr = old_stderr wfile.seek(0) body = list(wfile.readlines())[-1] self.assertEqual(body, b'HTTP_SOME_HEADER:good')
def test_strips_underscore_headers(self): """WSGIRequestHandler ignores headers containing underscores. This follows the lead of nginx and Apache 2.4, and is to avoid ambiguity between dashes and underscores in mapping to WSGI environ, which can have security implications. """ def test_app(environ, start_response): """A WSGI app that just reflects its HTTP environ.""" start_response('200 OK', []) http_environ_items = sorted( '%s:%s' % (k, v) for k, v in environ.items() if k.startswith('HTTP_') ) yield (','.join(http_environ_items)).encode('utf-8') rfile = BytesIO() rfile.write("GET / HTTP/1.0\r\n") rfile.write("Some-Header: good\r\n") rfile.write("Some_Header: bad\r\n") rfile.write("Other_Header: bad\r\n") rfile.seek(0) # WSGIRequestHandler closes the output file; we need to make this a # no-op so we can still read its contents. class UnclosableBytesIO(BytesIO): def close(self): pass wfile = UnclosableBytesIO() def makefile(mode, *a, **kw): if mode == 'rb': return rfile elif mode == 'wb': return wfile request = Stub(makefile=makefile) server = Stub(base_environ={}, get_app=lambda: test_app) # We don't need to check stderr, but we don't want it in test output old_stderr = sys.stderr sys.stderr = StringIO() try: # instantiating a handler runs the request as side effect WSGIRequestHandler(request, '192.168.0.2', server) finally: sys.stderr = old_stderr wfile.seek(0) body = list(wfile.readlines())[-1] self.assertEqual(body, 'HTTP_SOME_HEADER:good')
def get(self, key): """ Regenerates a MultiValueDict instance containing the files related to all file states stored for the given key. """ upload = None files_states = self.backend.get(key) files = MultiValueDict() if files_states: for name, state in files_states.items(): f = BytesIO() f.write(state['content']) # If the post is too large, we cannot use a # InMemoryUploadedFile instance. if state['size'] > settings.FILE_UPLOAD_MAX_MEMORY_SIZE: upload = TemporaryUploadedFile( state['name'], state['content_type'], state['size'], state['charset'], ) upload.file = f else: f = BytesIO() f.write(state['content']) upload = InMemoryUploadedFile( file=f, field_name=name, name=state['name'], content_type=state['content_type'], size=state['size'], charset=state['charset'], ) files[name] = upload # Go to the first byte in the file for future use upload.file.seek(0) return files
def add_event(request, me): """ 创建活动 """ if request.method == 'POST': # 获取表单提交数据 name = request.POST['name'] time = request.POST['time'] address = request.POST['address'] introduce = request.POST['introduce'] event_img = request.FILES['event_img'] # 生成二维码 # 保存表单数据 event = Event.objects.create(name=name, time=time, address=address, introduce=introduce, event_img=event_img) qr = qrcode.make( 'https://pinkslash.metatype.cn/wechat_login/?status=provider_{0}'. format(event.id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='event.png', content_type='image/png', size=len(qr_data), charset=None) # 保存表单数据 event.qrcode = qr_img event.save() buf.close() return redirect('/events/')
def add_food(request, me): if request.method == 'POST': # 获取表单提交数据 name = request.POST['name'] credit = request.POST['credit'] # event_id = request.POST['event_id'] food_img = request.FILES['food_img'] event = me.event # 保存表单数据 food = Food.objects.create(name=name, provider=me, credit=credit, event=event, food_img=food_img) # 生成二维码 qr = qrcode.make( 'https://pinkslash.metatype.cn/wechat_login/?status=purchase_{0}_{1}' .format(event.id, food.id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='food.png', content_type='image/png', size=len(qr_data), charset=None) food.qrcode = qr_img food.save() buf.close() return redirect('/foods?eid={0}'.format(event.id))
def artist_add_from_melon(request): """ 1. artist_search_from_melon.html에 form을 작성 (action이 현재 이 view로 올 수 있도록), POST메서드 필요한 요소는 csrf_token과 type=hidden으로 전달하는 artist_id값 <input type="hidden" value="{{ artist_info.artist_id }}"> button submit (추가하기) 2. 작성한 form POST요청을 받음 (추가하기 버튼 클릭) request.POST['artist_id'] artist_id를 사용해서 멜론사이트에서 Artist에 들어갈 상세정보들을 가져옴 name real_name nationality birth_date constellation blood_type intro 1) 위 데이터를 그대로 HttpResponse로 출력해보기 2) 잘 되면 채운 Artist를 생성, DB에 저장 이후 artist:artist-list로 redirect :param request: :return: """ if request.method == 'POST': artist_id = request.POST['artist_id'] artist = ArtistData(artist_id) artist.get_detail() name = artist.name real_name = artist.personal_information.get('본명', '') nationality = artist.personal_information.get('국적', '') birth_date_str = artist.personal_information.get('생일', '') constellation = artist.personal_information.get('별자리', '') blood_type = artist.personal_information.get('혈액형', '') for short, full in Artist.CHOICES_BLOOD_TYPE: if blood_type.strip() == full: blood_type = short break else: blood_type = Artist.BLOOD_TYPE_OTHER # artist_id가 melon_id에 해당하는 Artist가 이미 있다면 # 해당 Artist의 내용을 update # 없으면 Artist를 생성 response = request.get(url_img_cover) binary_data = response.content temp_file = BytesIO() temp_file.write(binary_data) Artist.objects.update_or_create(melon_id=artist_id, defaults={ 'name': name, 'real_name': real_name, 'nationality': nationality, 'birth_date': datetime.strptime( birth_date_str, '%Y.%m.%d'), 'constellation': constellation, 'blood_type': blood_type, }) return redirect('artist:artist-list')
def mini_login(status, code, userInfo): appid = 'wx8c822d6f747d1e6a' secret = '2419917cec1c48a0e421a9e3513f754e' url = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code'.format( appid, secret, code) res = requests.get(url) res = json.loads(res.text) unionid = res['unionid'] user = User.objects.filter(union_id=unionid).first() print('code', code) print('userInfo', userInfo) print('res', res) print('status', status) event = Event.objects.all().first() if status == 'firstLogin': if user: if user.name and user.hotel_name: return { 'url': 'https://pinkslash.metatype.cn/customer_profile/{0}/'. format(user.id) } else: return { 'url': 'https://pinkslash.metatype.cn/mini_customer/save_message/{0}/' .format(user.id) } else: head_img = userInfo['userInfo']['avatarUrl'] user = User.objects.create(union_id=unionid, head_img=head_img, event=event, status=0) print('user', user) qr = qrcode.make( 'http://pinkslash.metatype.cn/wechat_login/?status=sendcredits_{0}_{1}' .format(user.id, event.id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='food.png', content_type='image/png', size=len(qr_data), charset=None) _user = User.objects.get(id=user.id) _user.qrcode = qr_img _user.save() print('_user', _user) return { 'url': 'https://pinkslash.metatype.cn/mini_customer/save_message/{0}/' .format(user.id) } else: return { 'url': 'https://pinkslash.metatype.cn/customer_profile/{0}/'.format( user.id) }
def wechat_login(request): full_path = request.get_full_path() if 'code' in full_path: code = request.GET.get('code') user_data = wechat_api(code) nickname = user_data['nickname'] union_id = user_data['union_id'] head_img = user_data['head_img'] user = User.objects.filter(union_id=union_id).first() status = request.GET.get('status') if user: request.session['uid'] = user.id if user.status == 1: if 'purchase' in full_path: return HttpResponse("Food providers cannot buy food") if user.name and user.username: return redirect('/get_provider_info/{0}/'.format(user.id)) else: return redirect('/provider/save_message/') elif user.status == 0: if 'purchase' in full_path: if user.name and user.hotel_name: food_id = status.split('_')[2] food = Food.objects.filter(id=food_id).first() return redirect('/food_purchase/{0}/'.format(food.id)) # if user.credit >= food.credit: # if (user.credit-food.credit) >= (-1650): # user.credit -= food.credit # user.save() # provider = food.provider # provider.credit += food.credit # provider.save() # History.objects.create( # user=user, credit='-{0}'.format(str(food.credit)), desc='Buying Food') # History.objects.create( # user=provider, credit='+{0}'.format(str(food.credit)), desc='Selling Food') # UserFood.objects.create(user=user, food=food) # return redirect('/pay_success') # else: # return redirect('/pay_failed') else: return redirect('/customer/save_message/') elif 'sendcredits' in full_path: receiver_id = status.split('_')[1] if str(user.id) == receiver_id: return redirect('/customer_profile/{0}/'.format( user.id)) ctx = {'receiver_id': receiver_id} return render(request, 'presentation.html', ctx) try: credit = status.split('_')[2] except BaseException: return HttpResponse( 'Customers cannot log in as food providers') # 2019.5.20 by jiangyuwei # 功能:如果这个码是一个用户只能扫一次的,就将其id取出来去表中查这个数据 # 如果查得到就说明已经扫过了,返回`You have scanned the QR code` # 如果查不到说明没扫过,在取出user_id并且在表中添加一条数据,最后将积分加上 if 'customeronce' in full_path: if user.name and user.hotel_name: try: only_credit_id = status.split('_')[3] except BaseException: only_credit_id = None user_scan = UserScan.objects.filter(user=user) if user_scan: # return HttpResponse('You have scanned the QR code') return redirect('/customer_profile/{0}/'.format( user.id)) else: try: # 在表中添加当前用户扫描某一个二维码的记录 once_credit = OnlyOnceCredit.objects.get( pk=only_credit_id) UserScan.objects.create(user=user, credit=once_credit) except BaseException: return HttpResponse('Please scan again') else: return redirect('/customer/save_message/') if user.name and user.hotel_name: # user.credit += int(credit) # user.save() # History.objects.create(user=user, # credit='+{0}'.format(str(credit)), # desc='Scanning QRCode') # UserCredit.objects.create(user=user, credit=credit) return redirect('/customer_profile/{0}/'.format(user.id)) else: return redirect('/customer/save_message/') else: event_id = status.split('_')[1] event = Event.objects.filter(id=int(event_id)).first() if 'provider' in full_path: user = User.objects.create(union_id=union_id, head_img=head_img, status=1, event=event) request.session['uid'] = user.id return redirect('/provider/save_message/') elif 'customer' in full_path: credit = status.split('_')[2] user = User.objects.create(union_id=union_id, head_img=head_img, status=0, event=event, credit=int(credit)) if 'customeronce' in full_path: # 取出credit_id only_credit_id = status.split('_')[3] print("219 219**************", only_credit_id) # 在用户已经扫描的表中添加一条 新用户扫描该二维码的数据 once_credit = OnlyOnceCredit.objects.get(pk=only_credit_id) UserScan.objects.create(credit=once_credit, user=user) History.objects.create(user=user, credit='+{0}'.format(str(credit)), desc='Scanning QRCode') UserCredit.objects.create(user=user, credit=str(credit)) request.session['uid'] = user.id # 用户第一次登陆时生成赠送积分二维码 qr = qrcode.make( 'https://pinkslash.metatype.cn/wechat_login/?status=sendcredits_{0}_{1}' .format(user.id, event_id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='user.png', content_type='image/png', size=len(qr_data), charset=None) _user = User.objects.get(id=user.id) _user.qrcode = qr_img _user.save() return redirect('/customer/save_message/') # return redirect('/customer_profile/{0}/'.format(user.id)) elif 'sendcredits' in full_path: event_id = status.split('_')[2] event = Event.objects.filter(id=int(event_id)).first() user = User.objects.create(union_id=union_id, head_img=head_img, status=0, event=event) request.session['uid'] = user.id qr = qrcode.make( 'https://pinkslash.metatype.cn/wechat_login/?status=sendcredits_{0}_{1}' .format(user.id, event_id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='user.png', content_type='image/png', size=len(qr_data), charset=None) _user = User.objects.get(id=user.id) _user.qrcode = qr_img _user.save() return redirect('/customer/save_message/') elif 'purchase' in full_path: user = User.objects.create(union_id=union_id, head_img=head_img, status=0, event=event) request.session['uid'] = user.id qr = qrcode.make( 'https://pinkslash.metatype.cn/wechat_login/?status=sendcredits_{0}_{1}' .format(user.id, event_id)) buf = BytesIO() qr.save(buf) qr_data = buf.getvalue() buf.write(qr_data) qr_img = InMemoryUploadedFile(file=buf, field_name=None, name='user.png', content_type='image/png', size=len(qr_data), charset=None) _user = User.objects.get(id=user.id) _user.qrcode = qr_img _user.save() return redirect('/customer/save_message/') else: redirect_uri = 'https://pinkslash.metatype.cn' + full_path get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7594d7d49e0235f&redirect_uri=" + \ redirect_uri + "&response_type=code&scope=snsapi_userinfo" return redirect(get_code_url) return HttpResponse("xixi")