def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.code: # generate unique 5 digit (or more) code code = random.randint(10000, 999999999) # check that generated code is unique while Coupon.objects.filter(code=code).count() > 0: code = random.randint(10000, 999999999) self.code = code super(Coupon, self).save(force_insert, force_update, using, update_fields)
def getContent(url): html = get_html(url) # html = '<!DOCTYPE html> <!--[if IE 6]><html class="ie lt-ie8"><![endif]--> <!--[if IE 7]><html class="ie lt-ie8"><![endif]--> <!--[if IE 8]><html class="ie ie8"><![endif]--> <!--[if IE 9]><html class="ie ie9"><![endif]--> <!--[if !IE]><!--> <html> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"> <!-- Start of Baidu Transcode --> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta http-equiv="Cache-Control" content="no-transform" /> <meta name="applicable-device" content="pc,mobile"> <meta name="MobileOptimized" content="width"/> <meta name="HandheldFriendly" content="true"/> <meta name="mobile-agent" content="format=html5;url=http://www.jianshu.com/p/a88c174098d2"> <!-- End of Baidu Transcode --> <meta name="description" content="坦白地承认,目前正说明处于人生最为动荡迷茫的时期,与其任由自己惶惶然不如进行一场关于独处的修炼,一场手绘修炼。 #修炼第一章,小猫名叫haru。"> <meta name="360-site-verification" content="604a14b53c6b871206001285921e81d8" /> <meta property="wb:webmaster" content="294ec9de89e7fadb" /> <meta property="qc:admins" content="104102651453316562112116375" /> <meta property="qc:admins" content="11635613706305617" /> <meta property="qc:admins" content="1163561616621163056375" /> <meta name="google-site-verification" content="cV4-qkUJZR6gmFeajx_UyPe47GW9vY6cnCrYtCHYNh4" /> <meta name="google-site-verification" content="HF7lfF8YEGs1qtCE-kPml8Z469e2RHhGajy6JPVy5XI" /> <meta http-equiv="mobile-agent" content="format=html5; url=http://www.jianshu.com/p/a88c174098d2"> <!-- Apple --> <meta name="apple-mobile-web-app-title" content="简书"> <!-- Meta for Smart App Banner --> <meta name="apple-itunes-app" content="app-id=888237539, app-argument=jianshu://notes/18751496"> <!-- End --> <!-- Meta for Twitter Card --> <meta content="summary" property="twitter:card"> <meta content="@jianshucom" property="twitter:site"> <meta content="水彩猫" property="twitter:title"> <meta content="坦白地承认,目前正说明处于人生最为动荡迷茫的时期,与其任由自己惶惶然不如进行一场关于独处的修炼,一场手绘修炼。 #修炼第一章,小猫名叫haru。" property="twitter:description"> <meta content="http://www.jianshu.com/p/a88c174098d2" property="twitter:url"> <!-- End --> <!-- Meta for OpenGraph --> <meta property="fb:app_id" content="865829053512461"> <meta property="og:site_name" content="简书"> <meta property="og:title" content="水彩猫"> <meta property="og:type" content="article"> <meta property="og:url" content="http://www.jianshu.com/p/a88c174098d2"> <meta property="og:description" content="坦白地承认,目前正说明处于人生最为动荡迷茫的时期,与其任由自己惶惶然不如进行一场关于独处的修炼,一场手绘修炼。 #修炼第一章,小猫名叫haru。"> <!-- End --> <!-- Meta for Facebook Applinks --> <meta property="al:ios:url" content="jianshu://notes/18751496" /> <meta property="al:ios:app_store_id" content="888237539" /> <meta property="al:ios:app_name" content="简书" /> <meta property="al:android:url" content="jianshu://notes/18751496" /> <meta property="al:android:package" content="com.jianshu.haruki" /> <meta property="al:android:app_name" content="简书" /> <!-- End --> <title>水彩猫 - 简书</title> <meta name="csrf-param" content="authenticity_token" /> <meta name="csrf-token" content="EMJVgIPfzO/dvydstqga7E4W40/KVyxL7d4HyjKIfUyGxODCgc9jdW/mfVdTuTM7PIokdc5WE4Ee5xR6dOVz6w==" /> <link rel="stylesheet" media="all" href="//cdn2.jianshu.io/assets/web-b6ffb2ef57d077ea3cf8.css" /> <link rel="stylesheet" media="all" href="//cdn2.jianshu.io/assets/web/pages/notes/show/entry-319cd8f71e179151094e.css" /> <link href="//cdn2.jianshu.io/assets/favicons/favicon-03411b154a430b85d807b4366489c21122fb983a38f3d7ca926f882e6367b13e.ico" rel="icon"> <link rel="apple-touch-icon-precomposed" href="//cdn2.jianshu.io/assets/apple-touch-icons/57-a6f1f1ee62ace44f6dc2f6a08575abd3c3b163288881c78dd8d75247682a4b27.png" sizes="57x57" /> <link rel="apple-touch-icon-precomposed" href="//cdn2.jianshu.io/assets/apple-touch-icons/72-fb9834bcfce738fd7b9c5e31363e79443e09a81a8e931170b58bc815387c1562.png" sizes="72x72" /> <link rel="apple-touch-icon-precomposed" href="//cdn2.jianshu.io/assets/apple-touch-icons/76-49d88e539ff2489475d603994988d871219141ecaa0b1a7a9a1914f4fe3182d6.png" sizes="76x76" /> <link rel="apple-touch-icon-precomposed" href="//cdn2.jianshu.io/assets/apple-touch-icons/114-24252fe693524ed3a9d0905e49bff3cbd0228f25a320aa09053c2ebb4955de97.png" sizes="114x114" /> <link rel="apple-touch-icon-precomposed" href="//cdn2.jianshu.io/assets/apple-touch-icons/120-1bb7371f5e87f93ce780a5f1a05ff1b176828ee0d1d130e768575918a2e05834.png" sizes="120x120" /> <link rel="apple-touch-icon-precomposed" href="//cdn2.jianshu.io/assets/apple-touch-icons/152-bf209460fc1c17bfd3e2b84c8e758bc11ca3e570fd411c3bbd84149b97453b99.png" sizes="152x152" /> <!-- Start of 访问统计 --> <script> (function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\'); ga(\'create\', \'UA-35169517-1\', \'auto\'); ga(\'send\', \'pageview\'); </script> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "//hm.baidu.com/hm.js?0c0e9d9b1e7d617b3e6842e85b9fb068"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <!-- End of 访问统计 --> </head> <body lang="zh-CN" class="reader-song-font"> <!-- 全局顶部导航栏 --> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="width-limit"> <!-- 左上方 Logo --> <a class="logo" href="/"><img src="//cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png" alt="Logo" /></a> <!-- 右上角 --> <!-- 未登录显示登录/注册/写文章 --> <a class="btn write-btn" target="_blank" href="/writer#/"> <i class="iconfont ic-write"></i>写文章 </a> <a class="btn sign-up" href="/sign_up">注册</a> <a class="btn log-in" href="/sign_in">登录</a> <!-- 如果用户登录,显示下拉菜单 --> <div id="view-mode-ctrl"> </div> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu" aria-expanded="false"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="menu"> <ul class="nav navbar-nav"> <li class=""> <a href="/"> <span class="menu-text">首页</span><i class="iconfont ic-navigation-discover menu-icon"></i> </a> </li> <li class=""> <a class="app-download-btn" href="/apps"><span class="menu-text">下载App</span><i class="iconfont ic-navigation-download menu-icon"></i></a> </li> <li class="search"> <form target="_blank" action="/search" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" /> <input type="text" name="q" id="q" value="" autocomplete="off" placeholder="搜索" class="search-input" /> <a class="search-btn" href="javascript:void(null)"><i class="iconfont ic-search"></i></a> </form> </li> </ul> </div> </div> </div> </nav> <div class="note"> <div class="post"> <div class="article"> <h1 class="title">水彩猫</h1> <!-- 作者区域 --> <div class="author"> <a class="avatar" href="/u/cb069f2908da"> <img src="//upload.jianshu.io/users/upload_avatars/7960276/e89d74d9-3f7e-4164-8577-e41ce26f404e?imageMogr2/auto-orient/strip|imageView2/1/w/96/h/96" alt="96" /> </a> <div class="info"> <span class="name"><a href="/u/cb069f2908da">花架与花</a></span> <!-- 关注用户按钮 --> <div props-data-classes="user-follow-button-header" data-author-follow-button></div> <!-- 文章数据信息 --> <div class="meta"> <!-- 如果文章更新时间大于发布时间,那么使用 tooltip 显示更新时间 --> <span class="publish-time">2017.10.24 14:23</span> <span class="wordage">字数 67</span> </div> </div> <!-- 如果是当前作者,加入编辑按钮 --> </div> <!-- --> <!-- 文章内容 --> <div data-note-content class="show-content"> <p>坦白地承认,目前正说明处于人生最为动荡迷茫的时期,与其任由自己惶惶然不如进行一场关于独处的修炼,一场手绘修炼。<br></p><p>#修炼第一章,小猫名叫haru。</p><div class="image-package"> <img src="//upload-images.jianshu.io/upload_images/7960276-f2f63821e5fd5ea5.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"><br><div class="image-caption">图片发自简书App</div> </div> </div> <!-- --> <div class="show-foot"> <a class="notebook" href="/nb/16605344"> <i class="iconfont ic-search-notebook"></i> <span>日记本</span> </a> <div class="copyright" data-toggle="tooltip" data-html="true" data-original-title="转载请联系作者获得授权,并标注“简书作者”。"> © 著作权归作者所有 </div> <div class="modal-wrap" data-report-note> <a id="report-modal">举报文章</a> </div> </div> </div> <!-- 文章底部作者信息 --> <div class="follow-detail"> <div class="info"> <a class="avatar" href="/u/cb069f2908da"> <img src="//upload.jianshu.io/users/upload_avatars/7960276/e89d74d9-3f7e-4164-8577-e41ce26f404e?imageMogr2/auto-orient/strip|imageView2/1/w/96/h/96" alt="96" /> </a> <div props-data-classes="user-follow-button-footer" data-author-follow-button></div> <a class="title" href="/u/cb069f2908da">花架与花</a> </div> </div> <div class="support-author"></div> <div class="meta-bottom"> <div class="btn like-group"></div> <div class="share-group"> <a class="share-circle" data-action="weixin-share" data-toggle="tooltip" data-original-title="分享到微信"> <i class="iconfont ic-wechat"></i> </a> <a class="share-circle" data-action="weibo-share" data-toggle="tooltip" href="javascript:void((function(s,d,e,r,l,p,t,z,c){var%20f='http://v.t.sina.com.cn/share/share.php?appkey=1881139527',u=z||d.location,p=['&url=',e(u),'&title=',e(t||d.title),'&source=',e(r),'&sourceUrl=',e(l),'&content=',c||'gb2312','&pic=',e(p||'')].join('');function%20a(){if(!window.open([f,p].join(''),'mb',['toolbar=0,status=0,resizable=1,width=440,height=430,left=',(s.width-440)/2,',top=',(s.height-430)/2].join('')))u.href=[f,p].join('');};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else%20a();})(screen,document,encodeURIComponent,'','','http://cwb.assets.jianshu.io/notes/images/18751496/weibo/image_0a19c655fca5.jpg', '推荐 花架与花 的文章《水彩猫》( 分享自 @简书 )','http://www.jianshu.com/p/a88c174098d2?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=weibo','页面编码gb2312|utf-8默认gb2312'));" data-original-title="分享到微博"> <i class="iconfont ic-weibo"></i> </a> <a class="share-circle" data-toggle="tooltip" href="http://cwb.assets.jianshu.io/notes/images/18751496/weibo/image_0a19c655fca5.jpg" target="_blank" data-original-title="下载长微博图片"> <i class="iconfont ic-picture"></i> </a> <a class="share-circle more-share" tabindex="0" data-toggle="popover" data-placement="top" data-html="true" data-trigger="focus" href="javascript:void(0);" data-content=\' <ul class="share-list"> <li><a href="javascript:void(function(){var d=document,e=encodeURIComponent,r='http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url='+e('http://www.jianshu.com/p/a88c174098d2?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=qzone')+'&title='+e('推荐 花架与花 的文章《水彩猫》'),x=function(){if(!window.open(r,'qzone','toolbar=0,resizable=1,scrollbars=yes,status=1,width=600,height=600'))location.href=r};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})();"><i class="social-icon-sprite social-icon-zone"></i><span>分享到QQ空间</span></a></li> <li><a href="javascript:void(function(){var d=document,e=encodeURIComponent,r='https://twitter.com/share?url='+e('http://www.jianshu.com/p/a88c174098d2?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=twitter')+'&text='+e('推荐 花架与花 的文章《水彩猫》( 分享自 @jianshucom )')+'&related='+e('jianshucom'),x=function(){if(!window.open(r,'twitter','toolbar=0,resizable=1,scrollbars=yes,status=1,width=600,height=600'))location.href=r};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})();"><i class="social-icon-sprite social-icon-twitter"></i><span>分享到Twitter</span></a></li> <li><a href="javascript:void(function(){var d=document,e=encodeURIComponent,r='https://www.facebook.com/dialog/share?app_id=483126645039390&display=popup&href=http://www.jianshu.com/p/a88c174098d2?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=facebook',x=function(){if(!window.open(r,'facebook','toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330'))location.href=r};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})();"><i class="social-icon-sprite social-icon-facebook"></i><span>分享到Facebook</span></a></li> <li><a href="javascript:void(function(){var d=document,e=encodeURIComponent,r='https://plus.google.com/share?url='+e('http://www.jianshu.com/p/a88c174098d2?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=google_plus'),x=function(){if(!window.open(r,'google_plus','toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330'))location.href=r};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})();"><i class="social-icon-sprite social-icon-google"></i><span>分享到Google+</span></a></li> <li><a href="javascript:void(function(){var d=document,e=encodeURIComponent,s1=window.getSelection,s2=d.getSelection,s3=d.selection,s=s1?s1():s2?s2():s3?s3.createRange().text:'',r='http://www.douban.com/recommend/?url='+e('http://www.jianshu.com/p/a88c174098d2?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=douban')+'&title='+e('水彩猫')+'&sel='+e(s)+'&v=1',x=function(){if(!window.open(r,'douban','toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330'))location.href=r+'&r=1'};if(/Firefox/.test(navigator.userAgent)){setTimeout(x,0)}else{x()}})()"><i class="social-icon-sprite social-icon-douban"></i><span>分享到豆瓣</span></a></li> </ul> \'>更多分享</a> </div> </div> <div id="vue_comment"></div> </div> <div class="vue-side-tool"></div> </div> <div class="note-bottom"> <div class="js-included-collections"></div> <div data-vcomp="recommended-notes" data-lazy="1.5" data-note-id="18751496"></div> </div> <script type="application/json" data-name="page-data">{"user_signed_in":false,"locale":"zh-CN","os":"other","read_mode":null,"read_font":null,"note_show":{"is_author":false,"is_following_author":false,"is_liked_note":false,"follow_state":0,"uuid":"771802ae-e4d0-4957-8dce-0dd04bc6a6b4"},"note":{"id":18751496,"slug":"a88c174098d2","user_id":7960276,"notebook_id":16605344,"commentable":true,"likes_count":0,"views_count":1,"public_wordage":67,"comments_count":0,"total_rewards_count":0,"is_author":false,"author":{"nickname":"花架与花","total_wordage":280,"followers_count":1,"total_likes_count":0}}}</script> <script src="//cdn2.jianshu.io/assets/babel-polyfill-676833c6a4d68573b4c3.js" crossorigin="anonymous"></script> <script src="//cdn2.jianshu.io/assets/web-base-f6535fa31c6f7630fbc1.js" crossorigin="anonymous"></script> <script src="//cdn2.jianshu.io/assets/web-66284f91873440622caf.js" crossorigin="anonymous"></script> <script src="//cdn2.jianshu.io/assets/web/pages/notes/show/entry-53cd167a1d5d33cd05fd.js" crossorigin="anonymous"></script> <script> (function(){ var bp = document.createElement(\'script\'); var curProtocol = window.location.protocol.split(\':\')[0]; if (curProtocol === \'https\') { bp.src = \'https://zz.bdstatic.com/linksubmit/push.js\'; } else { bp.src = \'http://push.zhanzhang.baidu.com/push.js\'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> </body> </html> ' soup = BeautifulSoup(html, 'lxml') divObj = soup.find('div', {'class': 'show-content'}) imagelist = divObj.find_all('div', {'class': 'image-package'}) currtime = time.localtime() # 创建保存图片的目录 dirname = time.strftime("%Y%m%d", currtime) realPath = settings.BASE_DIR + os.sep + 'common_static' + os.sep + 'images' + os.sep + 'jianshu' + os.sep + dirname path = os.altsep + 'common_static' + os.altsep + 'images' + os.altsep + 'jianshu' + os.altsep + dirname mkdir(realPath) imageprefix = time.strftime("%Y%m%d%H%M%S", currtime) for divimage in imagelist: image = divimage.find('img') imagesrc = image['src'] imagedata = requests.get('http:' + imagesrc).content imagename = imageprefix + str(random.randint(101, 999)) + '.png' with open(realPath + os.sep + imagename, 'wb') as f: f.write(imagedata) f.flush() f.close() image['src'] = path + os.altsep + imagename del image['data-original-src'] return str(divObj)
def user_enroll(request): if request.method == 'POST': print("post") # 获取提交的表单类 form = UserForm(request.POST) if form.is_valid(): print("a") # 获取电话号码 p = request.POST.get('phone') # 随机生成验证码 a = str() for i in range(5): num = str(random.randint(0, 9)) a = a + num # 向用户发送验证码 # send_sms(p, {'number': a}) # 将验证码写入session request.session['yzm'] = a request.session['phone'] = p f = request.session.get('yzm') print(f) # 设置过期时间 request.session.set_expiry(maxage) b = 1 return render(request, 'app/enroll.html', {'a': b, 'phone': p}) return render(request, 'app/enroll.html', {'form': form}) return render(request, 'app/enroll.html')
def randstr(length): rstr = "0123456789abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ" rstr_len = len(rstr) - 1 result = "" for i in range(length): result += rstr[random.randint(0, rstr_len)] return result
def password(request): print(2222222222222222222222222222) form1 = PW(request.POST) if form1.is_valid(): # 将手机号存入数据库 phone = request.session.get('phone') # User.objects.create(cellphone=p) # # 删除多余的repassword # del form1.cleaned_data['repassword'] # 保存到数据库密码 p = request.POST.get('password') p1 = hashlib.sha1(p.encode()).hexdigest() # 保存小米id xiaomiid = str() for i in range(10): num = str(random.randint(0, 9)) xiaomiid = xiaomiid + num User.objects.create(cellphone=phone, password=p1, xiaomiid=xiaomiid) # User.objects.create(**form1.cleaned_data) win = 'yes' return render(request, 'app/enroll.html', {'win': win, 'xiaomiid': xiaomiid}) c = 2 return render(request, 'app/enroll.html', {'c1': c, 'form1': form1})
def otp(request): if request.method == "POST": get_uname=request.POST.get('uname') get_pwd=request.POST.get('pwd') get_email=request.POST.get('email') get_number =request.POST.get('number') global get_uname,get_pwd,get_number,get_email for x in range(1000,9999): global otp otp = random.randint(1000,9999) break from django.core.mail import send_mail send_mail('Your OTP is', str(otp), '*****@*****.**', [get_email]) key = 'secret' encoded = jwt.encode({'pwd': get_pwd}, key, algorithm='HS256') # decoded = jwt.decode(encoded, key, algorithms='HS256') {'pwd': 'get_pwd'} login_details = Login.objects.create(username=get_uname,password= encoded,email= get_email ,contactno=get_number) # login_details =Login(username=get_uname,password= password,email= email) login_details.save() return render(request, "otp.html", {"Email":get_email})
def test_snippet_list_order_by_created_descending(self): """ Snippet List 의 결과가 생성일자 내림차순인지 확인 :return: """ for i in range(random.randint(5, 10)): Snippet.objects.create(code=f'a = {i}') response = self.client.get('/snippets/django_view/snippets/') data = json.loads(response.content) # snippets = Snippet.objects.order_by('-created') # # # response 에 전달된 JSON string 을 파싱한 Python 객체를 순회하며 'pk'값만 꺼냄 # data_pk_list = [] # for item in data: # data_pk_list.append(item['pk']) # # # Snippet.objects.order_by('-created') QuerySet 을 순회하며 각 Snippet 인스턴스의 pk 값만 꺼냄 # snippets_pk_list = [] # for snippet in snippets: # snippets_pk_list.append(snippet.pk) self.assertEqual( # list comprehension # data_pk_list, # JSON 으로 전달받은 데이터에서 pk만 꺼낸 리스트 [item['pk'] for item in data], # QuerySet.values_list(flat=True) # snippets_pk_list, # DB 에서 created 역순으로 pk 값만 가져온 QuerySet 으로 만든 리스트 list( Snippet.objects.order_by('-created').values_list('pk', flat=True)))
def signup(request): if request.method == "GET": return render(request, "signup.html") elif request.method == "POST": print("inside signup POST Method") get_uname = request.POST.get('name') get_pwd = request.POST.get('password') get_email = request.POST.get('Email') get_number = request.POST.get('no') print("get_uname ", get_uname) print("get_email ", get_email) for x in range(1000, 9999): Otp = random.randint(1000, 9999) print("Myyyyy Ottttppppppp=====", Otp) break try: login_details = Userdata.objects.create(username=get_uname, password=get_pwd, email=get_email, contactno=get_number) match_details =Otpdata.objects.create(otp=Otp, new=login_details) # todo_details=Tododata.objects.create(first=login_details) except Exception, e: print("Our Error=", str(e)) print("Number=", get_number) request.session['Email'] = get_email
def show_home(request): number = random.randint(0, 10) ids_generated = random.randint(0, 1000) if request.session.get('player_id') and request.session.get('game_id'): cur_game = Game.objects.get(game_id=request.session.get('game_id')) if cur_game.is_finished: if Game.objects.filter(is_finished=False).count() == 0: new_game = Game.objects.create(game_id=f'g{ids_generated}', is_finished=False, guessed_number=number) cur_player = Player.objects.get(player_id=request.session.get('player_id')) new_game.player_set = cur_player PlayerGameInfoAdd(new_game, cur_player, 0, True, True) request.session['game_id'] = f'g{ids_generated}' return redirect('/') else: cur_game = Game.objects.get(is_finished=False) cur_player = Player.objects.get(player_id=request.session.get('player_id')) cur_game.player_set = cur_player PlayerGameInfoAdd(cur_game, cur_player, 0, False, False) request.session['game_id'] = cur_game.game_id return redirect('/') else: cur_player = Player.objects.get(player_id=request.session.get('player_id')) if PlayerGameInfo.objects.all().filter(gameplay=cur_game).get(participant=cur_player).game_host: return redirect('/game-creator') else: return redirect('/gameplay') else: if Game.objects.filter(is_finished=False).count() == 0: new_game = Game.objects.create(game_id=f'g{ids_generated}', guessed_number=number, is_finished=False) new_player = Player.objects.create(player_id=f'p{ids_generated}') new_game.player_set = new_player PlayerGameInfoAdd(new_game, new_player, 0, True, True) request.session['player_id'] = f'p{ids_generated}' request.session['game_id'] = f'g{ids_generated}' return redirect('/') else: cur_game = Game.objects.get(is_finished=False) new_player = Player.objects.create(player_id=f'p{ids_generated}') cur_game.player_set = new_player PlayerGameInfoAdd(cur_game, new_player, 0, False, False) request.session['player_id'] = f'p{ids_generated}' request.session['game_id'] = cur_game.game_id return redirect('/')
def slug_generator(): """ Generates identification field for use inside of the system """ current_date = datetime.now() return u'%04d%02d%02d%02d%02d%02d%03d' % ( current_date.year, current_date.month, current_date.day, current_date.hour, current_date.minute, current_date.second, random.randint(0, 999) )
def add_posts_to_topic(board_id, topic_id, count=10): topic = Topic.objects.get(board_id=board_id, id=topic_id) randval = random.randint(1000, 10000) for i in range(0, 10): msg = f'post {randval}{i} for topic {board_id}-{topic_id}' print(msg) user = User.objects.first() post = Post.objects.create(message=msg, created_by=user, topic=topic).save()
def create(request): if request.method == "POST": new_str = request.session['goto'] + ", " + request.POST['goto'] low = int(request.POST['low']) high = int(request.POST['high']) request.session['goto'] = new_str request.session['new_gold'] = random.randint(low, high) request.session[ 'gold'] = request.session['gold'] + request.session['new_gold'] return redirect('/results')
def products_generate(): for i in range(1,6): c = Category.objects.get(code=i) Product.objects.all().filter(category=c).delete() for r in range(1,31): price = random.randint(10, 100) desc = randstring(300) p = Product(code= i + r,name='Товар ' + str(r)+str(i), category=c,price=price,description=desc) p.save()
def signup(request): if request.method == "GET": return render(request, "signup1.html") elif request.method == "POST": print("inside signup POST Method") get_uname = request.POST.get('name') get_pwd = request.POST.get('password') get_email = request.POST.get('Email') get_number = request.POST.get('no') print("get_uname ", get_uname) print("get_email ", get_email) # global get_uname,get_pwd,get_number,get_email for x in range(1000, 9999): # global otp Otp = random.randint(1000, 9999) break print(Otp) # email = EmailMessage('Subject', otpname, to=['get_email']) # email.send() from django.core.mail import send_mail send_mail('test email', str(Otp), '*****@*****.**', [get_email]) # key = 'secret' # encoded = jwt.encode({'pwd': 'get_pwd'}, key, algorithm='HS256') # decoded = jwt.decode(encoded, key, algorithms='HS256') # {'pwd': 'get_pwd'}\ try: login_details = Logins.objects.create(username=get_uname, password=get_pwd, email=get_email, contactno=get_number) match_details = New.objects.create(otp=Otp, new=login_details) # login_details.save() except Exception, e: print("Our Error=", str(e)) # login_details =Login(username=get_uname,password= password,email= email) # login_details.save() print("Number=", get_number) # JSON={"Email": get_email} # print("JJJJJJJJJJJJJSSSSSSSSSSSSOOOOONNNNN=",JSON) # return render(request, "otp1.html", {"Email": get_email}) # return HttpResponse (json.dumps({ # "Email": get_email, # "html": otp1.html}), # content_type="application/json") request.session['Email'] = get_email
def test_snippet_list_count(self): """ Snippet List 를 요청시 DB에 있는 자료수와 같은 갯수가 리턴되는지 확인 :return: """ for i in range(random.randint(10, 100)): Snippet.objects.create(code=f'a = {i}') response = self.client.get('/snippets/django_view/snippets/') data = json.loads(response.content) # response 로 받은 JSON 데이터의 길이와 # Snippet 테이블의 자료수(count)가 같은지 self.assertEqual(len(data), Snippet.objects.count())
def save_merchant(request): Name = request.POST.get("name") CONTACT = request.POST.get("contact") EMAIL = request.POST.get("email") Password = random.randint(10000000, 99999999) IdNo = gen_idno() MerchantModel(Merchant_Name=Name, Merchant_Contact=CONTACT, Merchant_Email=EMAIL, Merchant_Password=Password, Merchant_Id=IdNo).save() return render(request, "merchant.html", {"message": "merchant saved successfully"})
def entrance(request): try: m = Login.objects.get(email=request.POST['email']) password = request.POST['password'] if m.password == \ hashlib.sha1(str(password).encode('utf-8')).hexdigest(): request.session['member_id'] = m.id + random.randint(0, 1000) Session(name=m.name, session=request.session['member_id']).save() return HttpResponseRedirect("/chatRoom/") else: return HttpResponse("Ваши логин и пароль не соответствуют.") except Login.DoesNotExist: return HttpResponse("Ваши логин и пароль не соответствуют.")
def verify_phone(request): params = request.query_params phone = params['phone'] user = request.user profile = Profile.objects.filter(user=user).first() if user.is_authenticated(): pass elif not profile: profile = Profile.objects.create(user=user) if not profile.phone_verified: rand = random.randint(1001, 10000) if PendingAccount.objects.filter(phone=phone).count() < 10: PendingAccount.objects.create(phone=phone, verification_code=rand) else: messages.error(request, 'many attempts') return render(request, 'auth_page.html')
def create_profile(self, user, verification_type): """ Create a VerificationProfile for a given User """ if verification_type == 'email': salt = hashlib.sha1(str(random.random())).hexdigest()[:5] username = user.username if isinstance(username, unicode): username = username.encode('utf-8') verification_key = hashlib.sha1(salt+username).hexdigest() else: # for phone, random 4-digit codes verification_key = random.randint(1000, 9999) return self.model(user=user, verification_key=verification_key, type=verification_type, )
def auth(request): params = request.query_params phone = params['phone'] user = request.user password = params['pass'] if user.is_authenticated: return HttpResponse(True) # token = random.randint(1001, 10000) # return Response({"loggedin": True, 'token': token}) user = authenticate(request, username=phone, password=password) profile = Profile.objects.filter(user=user).first() if user and profile and profile.phone_verified: login(request, user) token = random.randint(1001, 10000) return HttpResponse(True) else: messages.error(request, 'نام کاربری یا رمز عبور اشتباه است!') return HttpResponse(False)
def verify_phone_view(request, phone, authorize_url): user = request.user if user.is_authenticated: return redirect(urllib.parse.unquote(authorize_url)) rand = random.randint(1001, 10000) r = requests.get( 'http://ip.sms.ir/SendMessage.ashx?user=9366697781&pass=zMUcxrE83uQWtCK&text=کد تایید شما: ' + str(rand) + '&to=' + phone + '&lineNo=50002015068678' ) if PendingAccount.objects.filter(phone=phone).count() < 10: PendingAccount.objects.create(phone=phone, verification_code=rand) else: messages.error(request, 'many attempts') form = EnteranceForm(fields_name=["phone", "code", "set_password"], fields_type=['CharField', 'CharField', 'CharField']) form.initial["phone"] = phone return render(request, 'auth_page.html', context={"form": form, 'next_url': "/auth/check_code_validity" + '?' + authorize_url})
def upload_image_path(instance, filename): new_filename = random.randint(1, 3934343433) name, ext = get_filename_ext(filename) final_filename = f'{new_filename}{ext}' return f'product_images/{new_filename}/{final_filename}'
def send_sms(phone, templateParam): client = AcsClient(SMSCONFIG['ACCESS_KEY_ID'], SMSCONFIG['ACCESS_KEY_SECRET'], 'default') request = CommonRequest() request.set_accept_format('json') request.set_domain('dysmsapi.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('RegionId', "cn-hangzhou") request.add_query_param('PhoneNumbers', phone) request.add_query_param('SignName', SMSCONFIG['SignName']) request.add_query_param('TemplateCode', SMSCONFIG['TemplateCode']) request.add_query_param('TemplateParam', templateParam) response = client.do_action(request) # python2: print(response) print(str(response, encoding='utf-8')) if __name__ == "__main__": a = str() for i in range(5): num = str(random.randint(0, 9)) a = a + num print(a) send_sms('13754834137', {'code': a})
def get_rand_name(path): name = "Tmp" + str(random.randint(0,100000)) return os.path.dirname(os.path.dirname(__file__)) + path + name
def pre_save(cls, sender, document, **kwargs): # from django.contrib.auth.hashers import make_password # document.password = make_password(document.password) if not document.api_key: document.api_key = get_random_string(random.randint(50, 60))
def random_integer(*args, **kwargs): return random.randint(-2147483648, 2147483647)
def nueva_pass(): #Genera pass aleatoria p = "" for _ in range(16): p += abc[random.randint(0, len(abc)-1)] return p