Best Python code snippet using autotest_python
views.py
Source:views.py
1import requests2from datetime import datetime3from django.http import HttpResponse, FileResponse4from django.shortcuts import render, redirect5from django.contrib.auth.models import User6from django.contrib.auth.decorators import login_required7from django.contrib import auth8from app import models9from app import function10def test(request):11 return HttpResponse("") # è¿åå符串12 return render(request, "") # è¿åä¸ä¸ªç½é¡µ13 return redirect('') # éå®å14# Create your views here.15#ç»å½16def login(request):17 if request.method == "POST":18 username = request.POST.get("username")19 password = request.POST.get('password')20 user_obj = auth.authenticate(username=username, password=password)21 if not user_obj:22 return render(request, "login.html", {'error': 'ç¨æ·åæè
å¯ç é误'})23 else:24 auth.login(request, user_obj)25 rep = redirect('/app/index')26 if user_obj.is_superuser:27 # rep = redirect('/app/list_work_admin')28 rep.set_cookie("is_superuser", True)29 else:30 # rep = redirect('/app/list_work')31 rep.set_cookie("is_superuser", False)32 rep.set_cookie("username", username, max_age=60 * 60 * 24 * 14) #设置cookieä¿å14天33 return rep34 else:35 return render(request, "login.html")36@login_required37def logout(request):38 auth.logout(request)39 rep = redirect("/app/login")40 rep.delete_cookie("username")41 rep.delete_cookie("is_superuser")42 return rep43def register(request):44 if request.method == "POST":45 username = request.POST.get("username")46 firstname = request.POST.get("firstname")47 password = request.POST.get("password")48 try:49 user = User.objects.get(username=username) # getè½ä¸ä»
è½è¿åä¸æ¡æ°æ®ã50 return render(request, "register.html", {'error': '该ç¨æ·å·²ç»åå¨'})51 except User.DoesNotExist:52 User.objects.create_user(username=username, password=password, first_name=firstname)53 return redirect("/app/login/") # éå®åè³ç»å½çé¢54 pass55 else:56 username = request.COOKIES.get('username')57 return render(request, "register.html", {'username': username})58@login_required59# åå§çé¢60def index(request):61 username = request.COOKIES.get('username')62 is_superuser = request.COOKIES.get("is_superuser")63 if username == 'root':64 flag = True65 else:66 flag = False67 return render(request, "index.html", {'username': username, 'is_superuser': is_superuser, 'flag': flag})68@login_required69# æ·»å ä½ä¸(管çå)70def add_work(request):71 is_superuser = request.COOKIES.get("is_superuser")72 if is_superuser == 'False':73 return redirect('/app/list_work')74 if request.method == 'POST':75 workname = request.POST.get('workname')76 deadline = request.POST.get('deadline')77 deadlinetime = request.POST.get('deadlinetime')78 email = request.POST.get('email')79 deadline = ' '.join([deadline, deadlinetime])80 t = models.Work.objects.create(name=workname, deadline=deadline, email=email)81 function.createDirectory('upload/' + str(t.id))82 return redirect("/app/list_work_admin") # éå®åè³ä½ä¸å表83 else:84 username = request.COOKIES.get('username')85 return render(request, "add_work.html", {'username': username, 'is_superuser': is_superuser})86@login_required87def add_userlist(request):88 is_superuser = request.COOKIES.get("is_superuser")89 if is_superuser == 'False':90 return redirect('/app/list_work')91 username = request.COOKIES.get("username")92 if username != 'root':93 return redirect('/app/index')94 if request.method == 'POST':95 path = 'upload/cache/åå.xlsx'96 obj = request.FILES.get('file')97 function.saveUploadedFile(obj, path)98 function.addUsers()99 return render(request, 'add_userlist.html', {'username': username, 'is_superuser': is_superuser, 'success': True})100 else:101 return render(request, 'add_userlist.html', {'username': username, 'is_superuser': is_superuser})102@login_required103# ä¸ä¼ ä½ä¸104def upload_work(request):105 username = request.COOKIES.get('username')106 is_superuser = request.COOKIES.get("is_superuser")107 student = User.objects.get(username=username)108 id = request.GET.get("id")109 if request.method == 'GET':110 return render(request, "upload_work.html", {'id': id, 'username': username, 'is_superuser': is_superuser})111 else:112 path = 'upload/{}/{}'.format(id, student.username + '+' + student.first_name)113 upload, _ = models.Upload.objects.get_or_create(username=username, work_id=id)114 upload.time = datetime.now()115 upload.save()116 obj = request.FILES.get('file')117 path += '.' + obj.name.split('.')[1]118 function.saveUploadedFile(obj, path)119 return render(request, "upload_work.html",120 {'id': id, 'username': username, 'is_superuser': is_superuser, 'success': True})121@login_required122# ç¨æ·ä½ä¸å表123def list_work(request):124 work_list = models.Work.objects.all()125 is_superuser = request.COOKIES.get("is_superuser")126 username = request.COOKIES.get('username')127 work = models.Upload.objects.filter(username=username)128 finish = []129 for i in work:130 finish.append(i.work_id)131 return render(request, "list_work.html",132 {'work_list': work_list, 'username': username, 'is_superuser': is_superuser, 'finish': finish})133@login_required134# 管çåä½ä¸å表135def list_work_admin(request):136 is_superuser = request.COOKIES.get("is_superuser")137 if is_superuser == 'False':138 return redirect('/app/list_work')139 work_list = models.Work.objects.all()140 username = request.COOKIES.get("username")141 work = models.Upload.objects.filter(username=username)142 finish = []143 for i in work:144 finish.append(i.work_id)145 return render(request, "list_work_admin.html",146 {'work_list': work_list, 'username': username, 'is_superuser': is_superuser, 'finish': finish})147@login_required148# 个人信æ¯149def detail(request):150 is_superuser = request.COOKIES.get("is_superuser")151 if request.method == "POST":152 first_name = request.POST.get('first_name')153 password = request.POST.get('password')154 username = request.GET.get("username")155 _t = User.objects.get(username=username)156 _t.first_name = first_name157 if password:158 _t.set_password(password)159 _t.save()160 return render(request, "detail.html", {'student': _t, 'username': username, 'is_superuser': is_superuser})161 else:162 username = request.COOKIES.get("username")163 student = User.objects.get(username=username)164 return render(request, "detail.html", {'student': student, 'username': username, 'is_superuser': is_superuser})165@login_required166# ä½ä¸ç¼è¾(管çå)167def edit(request):168 is_superuser = request.COOKIES.get("is_superuser")169 if is_superuser == 'False':170 return redirect('/app/list_work')171 if request.method == "GET":172 id = request.GET.get("id")173 work = models.Work.objects.get(id=id)174 username = request.COOKIES.get('username')175 return render(request, "edit.html", {'work': work, 'username': username, 'is_superuser': is_superuser})176 else:177 id = request.GET.get("id")178 workname = request.POST.get('workname')179 deadline = request.POST.get('deadline')180 deadlinetime = request.POST.get('deadlinetime')181 email = request.POST.get('email')182 _t = models.Work.objects.get(id=id)183 _t.name = workname184 _t.deadline = deadline + ' ' + deadlinetime185 _t.email = email186 _t.save()187 return redirect('/app/list_work_admin/')188@login_required189# ä½ä¸å é¤(管çå)190def delete(request):191 is_superuser = request.COOKIES.get("is_superuser")192 if is_superuser == 'False':193 return redirect('/app/list_work')194 id = request.GET.get("id")195 models.Work.objects.get(id=id).delete()196 # å é¤æ件夹197 function.deleteDirectory('upload/' + str(id))198 # å é¤ä¸ä½ä¸æå
³çè®°å½199 models.Upload.objects.filter(work_id=id).delete()200 return redirect('/app/list_work_admin/')201@login_required202def download(request):203 is_superuser = request.COOKIES.get("is_superuser")204 if is_superuser == 'False':205 return redirect('/app/list_work')206 username = request.COOKIES.get('username')207 if request.method == 'POST':208 id = request.GET.get('id')209 work = models.Work.objects.get(id=id)210 obj = request.FILES.get('file')211 if obj is None:212 path = 'upload/cache/åå.xlsx'213 else:214 path = 'upload/cache/' + str(id)215 path += '.' + obj.name.split('.')[1]216 function.saveUploadedFile(obj, path) # ä¿ååå217 print(id)218 function.writeRecord(path, id) # åå
¥å®ææ
åµ219 function.zipDirectory(id)220 new_path = 'upload/{}.zip'.format(id)221 file = open(new_path, 'rb')222 response = FileResponse(file)223 response['Content-Type'] = 'application/octet-stream'224 response['Content-Disposition'] = 'attachment;filename="{}.zip"'.format(work.name) # ä¸æ¯æä¸ææ件å225 return response226 else:227 id = request.GET.get('id')228 return render(request, "download.html", {'id': id, 'username': username, 'is_superuser': is_superuser})229@login_required230# ä¸è½½åå模æ¿231def download_template(request):232 file = open('static/files/模æ¿.xlsx', 'rb')233 response = FileResponse(file)234 response['Content-Type'] = 'application/octet-stream'235 response['Content-Disposition'] = 'attachment;filename="template.xlsx"' # ä¸æ¯æä¸ææ件å236 return response237@login_required238# ä¸è½½å¯¼å
¥åå模æ¿239def download_template1(request):240 file = open('static/files/导å
¥æ¨¡æ¿.xlsx', 'rb')241 response = FileResponse(file)242 response['Content-Type'] = 'application/octet-stream'243 response['Content-Disposition'] = 'attachment;filename="template.xlsx"' # ä¸æ¯æä¸ææ件å244 return response245@login_required246def list_user(request):247 is_superuser = request.COOKIES.get("is_superuser")248 if is_superuser == 'False':249 return redirect('/app/list_work')250 username = request.COOKIES.get('username')251 if username != 'root':252 return redirect('/app/index')253 if request.method == "POST":254 pass255 else:256 user_list = User.objects.all()257 return render(request, 'list_user.html',258 {'user_list': user_list, 'username': username, 'is_superuser': is_superuser})259@login_required260def edit_user(request):261 is_superuser = request.COOKIES.get("is_superuser")262 if is_superuser == 'False':263 return redirect('/app/list_work')264 username = request.COOKIES.get('username')265 if username != 'root':266 return redirect('/app/index')267 id = request.GET.get("id")268 user = User.objects.get(id=id)269 if request.method == "POST":270 superuser = request.POST.get("superuser")271 name = request.POST.get("first_name")272 password = request.POST.get("password")273 user.first_name = name274 user.is_superuser = superuser275 if password:276 user.set_password(password)277 user.save()278 return render(request, 'edit_user.html',279 {'user': user, 'username': username, 'is_superuser': is_superuser, 'success': True})280 else:281 return render(request, 'edit_user.html',282 {'user': user, 'username': username, 'is_superuser': is_superuser})283@login_required284def delete_user(request):285 is_superuser = request.COOKIES.get("is_superuser")286 if is_superuser == 'False':287 return redirect('/app/list_work')288 username = request.COOKIES.get('username')289 if username != 'root':290 return redirect('/app/index')291 id = request.GET.get("id")292 user = User.objects.get(id=id)293 user.delete()294 return redirect("/app/list_user")295@login_required296def add_user(request):297 is_superuser = request.COOKIES.get("is_superuser")298 if is_superuser == 'False':299 return redirect('/app/list_work')300 username = request.COOKIES.get('username')301 if username != 'root':302 return redirect('/app/index')303 if request.method == "POST":304 username = request.POST.get("username")305 name = request.POST.get("first_name")306 password = request.POST.get("password")307 superuser = request.POST.get("superuser")308 if superuser:309 User.objects.create_user(username=username, password=password,first_name=name)310 else:311 User.objects.create(username=name, password=password,first_name=name)312 return redirect('/app/list_user')313 else:314 return render(request, 'add_user.html',315 {'username': username, 'is_superuser': is_superuser})316#å®æ¶ä»»å¡317from apscheduler.schedulers.background import BackgroundScheduler318from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job319# å®ä¾åè°åº¦å¨320scheduler = BackgroundScheduler()321# è°åº¦å¨ä½¿ç¨é»è®¤çDjangoJobStore()322scheduler.add_jobstore(DjangoJobStore(), 'default')323# æ¯å¤©åéæ§è¡è¿ä¸ªä»»å¡324@register_job(scheduler, 'interval', id='test',seconds=60)325def test():326 # å
·ä½è¦æ§è¡ç代ç 327 function.checkDeadline()328# 注åå®æ¶ä»»å¡å¹¶å¼å§329register_events(scheduler)...
social_auth.py
Source:social_auth.py
1import requests2from django.conf import settings3from social_core.backends.azuread_tenant import AzureADTenantOAuth24from social_core.backends.github import GithubOAuth25from social_core.backends.okta import OktaOAuth26from social_core.backends.okta_openidconnect import OktaOpenIdConnect7# noinspection PyUnusedLocal8def fetch_github_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):9 org_name = getattr(settings, 'GITHUB_ADMIN_ORG_NAME', '')10 team_name = getattr(settings, 'GITHUB_ADMIN_TEAM_NAME', '')11 if not user or not isinstance(kwargs['backend'], GithubOAuth2) or not org_name or not team_name:12 return13 response = requests.post(14 url='https://api.github.com/graphql',15 headers={16 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),17 },18 json={19 'query': '''20 query($userName: String!, $orgName: String!, $teamName: String!) {21 organization(login: $orgName) {22 teams(query: $teamName, userLogins: [$userName], first: 1) {23 nodes {24 name25 }26 }27 }28 }29 ''',30 'variables': {31 'userName': details['username'],32 'orgName': org_name,33 'teamName': team_name,34 }35 }36 )37 response.raise_for_status()38 response = response.json()39 is_superuser = {'name': team_name} in response['data']['organization']['teams']['nodes']40 if user.is_superuser != is_superuser:41 user.is_superuser = is_superuser42 user.save()43# noinspection PyUnusedLocal44def fetch_azuread_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):45 group_id = getattr(settings, 'AZUREAD_ADMIN_GROUP_ID', '')46 if not user or not isinstance(kwargs['backend'], AzureADTenantOAuth2) or not group_id:47 return48 response = requests.post(49 url='https://graph.microsoft.com/v1.0/me/checkMemberGroups',50 headers={51 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),52 },53 json={54 'groupIds': [group_id]55 }56 )57 response.raise_for_status()58 response = response.json()59 is_superuser = group_id in response['value']60 if user.is_superuser != is_superuser:61 user.is_superuser = is_superuser62 user.save()63# noinspection PyUnusedLocal64def fetch_okta_oauth2_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):65 org_url = getattr(settings, 'SOCIAL_AUTH_OKTA_OAUTH2_API_URL', '')66 admin_group_name = getattr(settings, "OKTA_OAUTH2_ADMIN_GROUP_NAME", "")67 if not user or not isinstance(kwargs['backend'], OktaOAuth2):68 return69 # OktaOpenIdConnect inherits `OktaOAuth2`, so we have to explicitly skip OAuth2 trying70 # to fetch permissions when using OIDC backend.71 if isinstance(kwargs['backend'], OktaOpenIdConnect):72 return73 response = requests.post(74 url=f"{org_url}/v1/userinfo",75 headers={76 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),77 },78 )79 response.raise_for_status()80 response = response.json()81 is_superuser = admin_group_name in response.get("groups", [])82 is_staff = admin_group_name in response.get("groups", [])83 user_changed = False84 if user.is_superuser != is_superuser:85 user.is_superuser = is_superuser86 user_changed = user_changed or True87 if user.is_staff != is_staff:88 user.is_staff = is_staff89 user_changed = user_changed or True90 if user_changed:91 user.save()92# noinspection PyUnusedLocal93def fetch_okta_openidconnect_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):94 org_url = getattr(settings, 'SOCIAL_AUTH_OKTA_OPENIDCONNECT_API_URL', '')95 admin_group_name = getattr(settings, "OKTA_OPENIDCONNECT_ADMIN_GROUP_NAME", "")96 if not user or not isinstance(kwargs['backend'], OktaOpenIdConnect):97 return98 response = requests.post(99 url=f"{org_url}/v1/userinfo",100 headers={101 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),102 },103 )104 response.raise_for_status()105 response = response.json()106 is_superuser = admin_group_name in response.get("groups", [])107 is_staff = admin_group_name in response.get("groups", [])108 user_changed = False109 if user.is_superuser != is_superuser:110 user.is_superuser = is_superuser111 user_changed = user_changed or True112 if user.is_staff != is_staff:113 user.is_staff = is_staff114 user_changed = user_changed or True115 if user_changed:...
policys.py
Source:policys.py
...37 "condition": ["is_superuser"],38 "effect": "allow",39 },40 ]41 def is_superuser(self, request, view, action):42 return request.user.is_superuser43class CommentViewSetPolicy(AccessPolicy):44 statements = [45 {46 "principal": ["authenticated"],47 "action": ["create", "<safe_methods>"],48 "effect": "allow",49 },50 {51 "principal": ["authenticated"],52 "action": ["update", "partial_update", "destroy"],53 "condition": ["is_writer_or_superuser"],54 "effect": "allow",55 },56 ]57 def is_writer_or_superuser(self, request, view, action):58 writer = request.user59 comment = view.get_object()60 is_writer = comment.user is writer61 is_superuser = writer.is_superuser62 return is_writer or is_superuser63class CommentReportViewSetPolicy(AccessPolicy):64 statements = [65 {66 "principal": ["authenticated"],67 "action": ["create"],68 "effect": "allow",69 },70 {71 "principal": ["authenticated"],72 "action": ["list", "retrieve", "update", "partial_update", "delete"],73 "condition": ["is_superuser"],74 "effect": "allow",75 },76 ]77 def is_superuser(self, request, view, action):78 return request.user.is_superuser79class WorldcupViewSetPolicy(AccessPolicy):80 statements = [81 {82 "principal": ["*"],83 "action": ["<safe_methods>"],84 "effect": "allow",85 },86 {87 "principal": ["authenticated"],88 "action": ["create"],89 "effect": "allow",90 },91 {...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!