def active_user(request, token): #激活验证 try: username = token_confirm.confirm_validate_token(token) except: username = token_confirm.remove_validate_token(token) users = User.objects.filter(username=username) for user in users: if user.is_active == False: user.delete() return render( request, 'pc/message.html', { 'message': u'对不起,验证链接已经过期,请重新<a href=\"' + unicode(settings.DOMAIN) + u'/signup\">注册</a>' }) else: return render( request, 'pc/message.html', { 'message': u'此账号已经验证过,请重新<a href=\"' + unicode(settings.DOMAIN) + u'/signup\">注册</a>' }) try: user = User.objects.get(username=username) except User.DoesNotExist: return render(request, 'pc/message.html', {'message': u"对不起,您所验证的用户不存在,请重新注册"}) user.is_active = True user.save() message = u'验证成功,请进行<a href=\"' + unicode( settings.DOMAIN) + u'/login\">登录</a>操作' return render(request, 'pc/message.html', {'message': message})
def example_view(request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), 'is_authenticated': unicode(request.user.is_authenticated) # None } return Response(content)
def activate(request, token): """ 验证""" context = {"flag": False, "msg": '未知错误,请重新注册,或稍后重试!!!'} try: email = token_confirm.confirm_validate_token(token) except: # 令牌过期 token_confirm.remove_validate_token(token) context["msg"] = '半根蓝白博客站点提示您,验证链接已过期,请重新获取激活邮件' context["url"] = unicode(DOMAIN)+u'/accounts/reg' return render(request, 'accounts/user_active_result.html', context) try: user = User.objects.get(email=email) except User.DoesNotExist: context["msg"] = '半根蓝白博客站点提示您,您所验证的用户不存在' context["url"] = unicode(DOMAIN)+u'/accounts/reg/' return render(request, 'accounts/user_active_result.html', context) user.is_active = True user.save() token_confirm.remove_validate_token(token) # 移除此用户的token context["flag"] = True context["msg"] = '半根蓝白博客站点提示您,您的账户激活成功现在可以使用,' context["url"] = unicode(DOMAIN)+u'/accounts/profile' login(request, user) return render(request, 'accounts/user_active_result.html', context)
def export_as_csv(modeladmin, request, queryset): """ Generic csv export admin action. based on http://djangosnippets.org/snippets/1697/ """ opts = modeladmin.model._meta field_names = set([field.name for field in opts.fields]) if fields: fieldset = set(fields) field_names = field_names & fieldset elif exclude: excludeset = set(exclude) field_names = field_names - excludeset response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition'] = 'attachment; filename=%s.csv' % unicode( opts).replace('.', '_') writer = csv.writer(response) if header: writer.writerow(list(field_names)) for obj in queryset: writer.writerow([ unicode(getattr(obj, field)).encode("utf-8", "replace") for field in field_names ]) return response
def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content)
def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } competitors = Competitor.objects.all() serializer = CompetitorSerializer(competitors, many=True) return Response(serializer.data)
def get(self, request, format=None): content = { 'id': unicode(request.user.id), 'email': unicode(request.user), # `django.contrib.auth.User` instance. 'cedulaRuc': unicode(request.user.cedulaRuc), 'telefono': unicode(request.user.telefono), 'tipo': unicode(request.user.tipo.id), } return Response(content)
def __call__(self, values): try: if isinstance(values, string_types): return unicode(values).strip() elif len(values) > 1: return u' '.join(unicode(v).strip() for v in values) else: return values[0] except: return values
def list(self, request, *args, **kwargs): #queryset = User.objects.all().filter(username=request.user) #serializer = UserSerializer(queryset=queryset ,many=True) content = { 'user': unicode(request.user), 'groups': unicode(request.user.get_group_permissions()), 'permissions': unicode(request.user.get_all_permissions()) } return Response(content)
def get(self, request): content = { 'user': unicode( UserSerializer(request.user, context={ 'request': request }).data), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content)
def active_user(request, token): #激活验证 try: username = token_confirm.confirm_validate_token(token) except: username = token_confirm.remove_validate_token(token) users = User.objects.filter(username=username) for user in users: if user.is_active==False: user.delete() return render(request, 'pc/message.html', {'message': u'对不起,验证链接已经过期,请重新<a href=\"' + unicode(settings.DOMAIN) + u'/register\">注册</a>'}) else: return render(request, 'pc/message.html', {'message': u'此账号已经验证过,请重新<a href=\"' + unicode(settings.DOMAIN) + u'/register\">注册</a>'}) try: user = User.objects.get(username=username) except User.DoesNotExist: return render(request, 'pc/message.html', {'message': u'对不起,您所验证的用户不存在,请重新<a href=\"/register\">注册</a>'}) user.is_active = True user.save() msg = UserMessage() msg.user=user msg.to_user =User.objects.get(is_superuser=True) msg.message = '欢迎加入本站,在使用过程中有什么疑问,请联系管理员' msg.has_read = False msg.is_supper = True msg.save() message = u'验证成功,请进行<a href=\"' + unicode(settings.DOMAIN) + u'/login\">登录</a>操作' return render(request, 'pc/message.html', {'message':message})
def pre_save_petition_slug(sender, instance, *args, **kwargs): try: if not instance.slug: slug = slugify(translit(unicode(instance.title), reversed=True)) instance.slug = slug except BaseException: instance.slug = instance.title
def tag_search(request, tag, page_no): queryset = Recipe.objects.filter(tags__tag=slugify(unicode(tag))) tags_qset = Tag.objects.all() cuisine = Cuisine.objects.all() diettypes = DietType.objects.all() p = Paginator(queryset, 6) queryset = p.page(page_no).object_list li = list(p.page_range) nxt_pg = page_no + 1 prv_pg = page_no - 1 if nxt_pg > li[-1]: nxt_pg = page_no if prv_pg < 1: prv_pg = 1 rand_blog = list(BlogPost.objects.filter(show=True)) try: try: random_items = random.sample(rand_blog, 4) except: random_items = random.sample( rand_blog, BlogPost.objects.filter(show=True).count()) except: random_items = [] context = { 'all_recipes': queryset, 'tags': tags_qset, 'cuisine': cuisine, 'dietypes': diettypes, 'var_title': '{}'.format(tag + " recipes"), 'next': tag + "/" + str(nxt_pg), 'prev': tag + "/" + str(prv_pg), 'rand_blog': list(random_items) } return render(request, 'recipe/index.html', context)
def send_to_firebase(data): db = firestore.client() # start = time.time() # db.collection('notifications').document(str(uuid4())).create(raw_notification) # end = time.time() # spend_time = timedelta(seconds=end - start) # return spend_time user = User.objects.first() profile = Profile.objects.get(user=user) compressed_data = zlib.compress(profile.background.read()) b64_img = base64.b64encode(compressed_data) doc_ref = db.collection(u'background').document("2".__str__()) doc_ref.set({ u'username': user.username, u'background': profile.background.read() }) print("len", profile.background.read()) print("len", len(compressed_data)) users_ref = db.collection(u'background').document('2') get_bal = users_ref.get({u'background'}) x = u'{}'.format(get_bal.to_dict()['background']) users_ref = db.collection(u'background').document('2') get_bal = users_ref.get({u'username'}) bal = u'{}'.format(get_bal.to_dict()['username']) c = unicode(compressed_data, errors='replace') d = c.encode('utf-8') print(type(d), d[0:10]) print(compressed_data[0:10]) print(bytes(x[0:30], 'utf-8')) decompressed_byte_data = zlib.decompress(d)
def _clear_value(self, value): if isinstance(value, string_types): unicode = lambda s: str(s) try: cleared_value = unicode(remove_tags(value)) return parsers.normalize_spaces(cleared_value) except: return value else: return value
def get(self, request, *args, **kwargs): print ('Fill Volonters:') cat = CategoryResource.objects.all() surnames = [u'Мельник', u'Іванов', u'Калінін', u'Шемякін'] names = [u'Василь', u'Дмитро', u'Игорь', u'Антон'] znames = [u'Олександрович', u'Олексыйович', u'Константинович'] bt = [u'1989-03-19', u'1988-09-11', u'1987-12-19', u'1990-07-25'] operators = [u'093', u'050', u'098', u'066', u'099'] oblast = [u'Вінницька область', u'Волинська область', u'Дніпропетровська область', u'Донецька область', u'Закарпатська область', u'Запорізька область', u'Івано-Франківська область', u'Київська область', u'Кіровоградська область', u'Луганська область', u'Львівська область', u'Миколаївська область', u'Одеська область', u'Полтавська область', u'Рівненська область', u'Сумська область', u'Тернопільська область', u'Харківська область', u'Херсонська область', u'Хмельницька область', u'Черкаська область', u'Чернігівська область', u'Чернівецька область', u'Автономна Республіка Крим'] all_categories = list(CategoryResource.objects.all()) for i in range(5): telephone = u'+38' + random.choice(operators) + unicode(random.randint(1000000, 9999999)) fio = random.choice(surnames) + u' ' + random.choice(names) + u' ' + random.choice(znames) bth=random.choice(bt) address = random.choice(oblast) volonter = Volonter.objects.create( fio=fio, birthday=bth, address=address, telephone=telephone, gender=u'М', activeted=True, ) for i in range(random.randint(1, 2)): volonter.categories.add(random.choice(all_categories)) print (fio, telephone) return HttpResponse('ok')
def createDocxFile(header, content, images): document = Document() document.add_heading(header, 0) # document.add_paragraph(BeautifulSoup(content, 'html.parser').get_text()) # document.add_paragraph(content.strings.replace("<br>", "\\n")) for content_part in content: # if content_part.name == "blockquote" or content_part.name == "p": # print(content_part.string) if content_part.name == "ul" or content_part.name == "ol": for bullet in content_part.find_all('li'): print("-" + unicode(bullet.string))
def export_hosts(request): server = Server.objects.order_by('id') servers = server.values_list('in_ip', 'system_user__username', 'system_user__password', 'app_project__app_name_en', 'cpu_cores', 'cpu_count', 'mem', 'disk', 'groups__name', 'app_project__platform__name', 'idc__name', 'author__username', 'ctime') header_text = "IP,用户名,密码,服务名称,CPU核数,CPU个数,内存,磁盘,所属资产组,所属平台,IDC机房,创建者,创建时间" excel_name = unicode(u'服务器详细列表') headers = unicode(header_text).split(',') book = Workbook() sheet = book.create_sheet(title=excel_name, index=0) sheet.append(headers) if servers: for server in servers: serverList = list(server) sheet.append(serverList) else: logger.info('资产查询无数据') response = HttpResponse(content=save_virtual_workbook(book), content_type='application/msexcel') response['Content-Disposition'] = 'attachment; filename=servers_list.xlsx' return response
def test_unblock_user(self): #Arrange change_url = reverse("admin:accounts_user_changelist") object_list = User.objects.values_list('pk', flat=True) data = { 'action': 'unblock_users', django.contrib.admin.ACTION_CHECKBOX_NAME: [unicode(f) for f in object_list] } #Act self.client.post(change_url, data, follow=True) #Assert self.assertFalse(User.objects.filter(email='*****@*****.**')[0].blocked)
def test_marked_as_abusive_warnings_lower_then_2(self): #Arrange change_url = reverse("admin:chat_abusivechatmessage_changelist") object_list = AbusiveChatMessage.objects.values_list('pk', flat=True) data = { 'action': 'mark_as_abusive', django.contrib.admin.ACTION_CHECKBOX_NAME: [unicode(f) for f in object_list] } #Act response = self.client.post(change_url, data, follow=True) #Assert self.assertEqual(response.context["user"].warnings, 1)
def test_marked_as_nonabusive(self): #Arrange change_url = reverse("admin:chat_abusivechatmessage_changelist") object_list = AbusiveChatMessage.objects.values_list('pk', flat=True) data = { 'action': 'mark_as_nonabusive', django.contrib.admin.ACTION_CHECKBOX_NAME: [unicode(f) for f in object_list] } #Act self.client.post(change_url, data, follow=True) #Assert self.assertEqual( len(AbusiveChatMessage.objects.values_list('pk', flat=True)), 0)
def get(self, request, *args, **kwargs): ge_points = GeographyPoint.objects.all() storehouses = StoreHouse.objects.all() surnames = [u'Трэк', u'Троев', u'Атеистов', u'Трюкови', u'Спайдэр', u'Виннов'] names = [u'Вася', u'Акакий', u'Лео', u'Адольф', u'Иосиф', u'Дима', u'Игорь', u'Антон', u'Жора', u'Вася', u'Трион', u'Енот',] operators = [u'093', u'050', u'098', u'066', u'099'] point_cons = [] for point in ge_points: is_store = False is_point_con = False try: store = point.storehouse is_store = True except ObjectDoesNotExist: pass try: point_con = point.pointofconsuming is_point_con = True except ObjectDoesNotExist: pass if not is_store and not is_point_con: point_cons.append(point) # order = Order() # for need in order.need_set.all(): # pass # p = GeographyPoint() # p.storehouse # p.pointofconsuming for i in range(10): print (i) telephone1 = u'+38' + random.choice(operators) + unicode(random.randint(1000000, 9999999)) fio1 = random.choice(surnames) + u' ' + random.choice(names) point_cons1 = random.choice(list(point_cons)) point_cons.remove(point_cons1) PointOfConsuming.objects.create( geography_point = point_cons1, fio = fio1, telephone = telephone1, ) return HttpResponse('ok')
def test_marked_as_abusive_warnings_2(self): #Arrange change_url = reverse("admin:chat_abusivechatmessage_changelist") object_list = AbusiveChatMessage.objects.values_list('pk', flat=True) data = { 'action': 'mark_as_abusive', django.contrib.admin.ACTION_CHECKBOX_NAME: [unicode(f) for f in object_list] } self.user.warnings = 2 self.user.save() #Act self.client.post(change_url, data, follow=True) #Assert self.assertEqual( User.objects.filter(email='*****@*****.**')[0].warnings, 3)
def post(self, request, *args, **kwargs): # print('request.data: ', request.data) serializer = WriterLoginSerializer(data=request.data, context={'request': request}) # print(serializer) # print(dir(serializer)) data = {} if serializer.is_valid(raise_exception=True): # print('is_valid') writer = serializer.validated_data['writer'] # print(writer) serialized_writer = WriterDetailSerializer(writer).data # print(serialized_writer) data['writer'] = serialized_writer token, created = Token.objects.get_or_create(user=writer) data['token'] = unicode(token.key) else: data = serializer.errors return Response(data)
def extract(self): res = self.data try: # 去掉图片蒙版 res = res.replace('var occupyImg = ', '') bs = BeautifulSoup(res) # 去掉投票的iframe vote = bs.find('span', {'class': 'vote_area'}) if vote: vote.replace_with('') # 将图片和视频的宽高变为auto,src替换为data-src imgs = bs.select('img') for x in imgs: if x.get('style'): x['style'] = re.sub(r'(\w+px)', 'auto', x['style']) if x.get('data-src'): x['src'] = x.get('data-src') # 将视频的宽高设置为auto videos = bs.find_all('iframe', {'class': 'video_iframe'}) for item in videos: item['width'] = 'auto' item['height'] = 'auto' if item.get('src'): s = item.get('src') s = re.sub(r'(height=\d+[\.\d+]*)', 'height=auto', s) s = re.sub(r'(width=\d+[\.\d+]*)', 'width=auto', s) item['src'] = s if item.get('data-src'): s = item.get('data-src') s = re.sub(r'(height=\d+[\.\d+]*)', 'height=auto', s) s = re.sub(r'(width=\d+[\.\d+]*)', 'width=auto', s) item['data-src'] = s # if item.get('style'): # item['style'] = re.sub(r'(\w+px)', 'auto', item['style']) res = unicode(bs) except Exception as e: logger.exception(e) finally: return res
def make_order_view(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) request.session['total'] = cart.items.count() except: cart = Cart() cart.save() cart_id = cart.id request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) comp_id = 0 for i in cart.items.all(): comp_id = i.product.owner.id break form = OrderForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] phone = form.cleaned_data['phone'] comments = form.cleaned_data['comments'] new_order = Order() new_order.user = request.user new_order.owner = Company.objects.get(id=comp_id) new_order.save() new_order.items.add(cart) new_order.name = name new_order.phone = phone new_order.comments = comments new_order.total = cart.cart_total new_order.save() slug = slugify( translit(unicode('заказ' + str(new_order.id)), reversed=True)) new_order.slug = slug new_order.save() path = 'media/files/' + new_order.slug + '.xlsx' new_order.path = path new_order.save() del request.session['cart_id'] del request.session['total'] return HttpResponseRedirect(reverse('thanks'))
def set_grade(self, grade): """ set grade to decimal or letter if grade is less than 1 assume its a percentage returns success (True or False)""" try: grade = Decimal(str(grade)) if grade < 1: # assume grade is a percentage grade = grade * 100 self.grade = grade self.letter_grade = None return True except: grade = unicode.upper(unicode(grade)).strip() if grade in dict(self.letter_grade_choices): self.letter_grade = grade self.grade = None return True elif grade in ('', None, 'None'): self.grade = None self.letter_grade = None return True return False
def DownloadPdf(request, id): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # data=['Date', 'Employee Id', 'Department', 'Name', 'Clock-in', 'Clock-out', 'Late', 'Attendance'] # data.encode('utf-8') leads = get_object_or_404(LEADS, id=id) print(leads) print(type(leads)) lead = [ leads.company_name, leads.contact_number, leads.contact_person, leads.description, leads.website, leads.email, leads.source, leads.source_type, leads.assigned_boolean ] detail_string = u" ".join(unicode(obj) for obj in lead) p = canvas.Canvas(response) p.drawString(10, 800, detail_string) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response
def get_files(root_path, cur_path, allow_types=[]): files = [] items = os.listdir(cur_path) for item in items: item = unicode(item) item_fullname = os.path.join(root_path, cur_path, item).replace("\\", "/") if os.path.isdir(item_fullname): files.extend(get_files(root_path, item_fullname, allow_types)) else: ext = os.path.splitext(item_fullname)[1] is_allow_list = (len(allow_types) == 0) or (ext in allow_types) if is_allow_list: files.append({ "url": urljoin( USettings.gSettings.MEDIA_URL, os.path.join(os.path.relpath(cur_path, root_path), item).replace("\\", "/")), "mtime": os.path.getmtime(item_fullname) }) return files
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>') print(rel_soup.a['rel']) # 将tag转换成字符串是,多值属性合并为一个值 rel_soup.a['rel'] = ['index', 'contents'] print(rel_soup.p) # xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml') # print(xml_soup.p['class']) print(tag.string) print(type(tag.string)) # 转换为Unicode字符串 unicode_string = unicode(tag.string) print(unicode_string) ## 替换tag中的字符串 replace_with tag.string.replace_with('No longer bold') print(tag) print(soup.name) # 注释 markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>" soup = BeautifulSoup(markup) comment = soup.b.string print(type(comment)) # 提取的注释文本