Best Python code snippet using avocado_python
views.py
Source:views.py
1from django.shortcuts import render2# import pymongo34# Create your views here.5from django.http import HttpResponse,JsonResponse6from django.contrib.auth.decorators import login_required,permission_required78import datetime910import json11import requests1213#ä¸è½½14from django.http import StreamingHttpResponse1516import re17from app1.models import * #å¼ç¨181920@login_required(login_url = '/user/login.html')21def index(request):22 username = request.user.username23 return render(request, 'test1v.html', locals())242526status_dict = {27 True:"å¨åº",28 False:"åºåº"29}3031type_dict = {32 0:"å·²å
¥åº",33 1: "å·²åºåº",34 2: "å¼å¸¸åºåº",35}3637@login_required(login_url = '/user/login.html')38def test(request):39 # username = request.user.username40 username = "abc"41 recv = request.GET.dict()42 print(recv)43 kind = recv["kind"]44 ret = {}45 ####46 #æå
¥47 if kind=='0':48 #å¤æä¿¡æ¯æ¯å¦è¶³å¤49 data = json.loads(recv['data'])50 print(data)5152 #å¦æè¶³å¤ [å称ï¼ä»·æ ¼ï¼å§åï¼å¡å·ï¼å¤æ³¨]53 if data[0]!= None and data[1]!= None and data[2]!=None and data[3]!=None:54 #temp_id55 #æ¥è¯¢å·²ææ°é56 temp_id = len(Products.objects.filter())57 #å
¥åº58 Products.objects.create(name=data[0],price=data[1],operator=data[2],numid=temp_id,cardid=data[3])59 print("insert",temp_id)60 ret['status'] = 'ok'61 #è¿å对åºçidå·62 ret["id"] = temp_id63 #å
¥åºè®°å½64 temp_id2 = len(AlertLog.objects.filter())65 if data[4]==None:66 data[4] = ""67 AlertLog.objects.create(productname=data[0],productnumid=temp_id,numid=temp_id2,type=0,comments = data[4]) #0表示å
¥åº68 else:69 ret['status'] = "lack"7071 return JsonResponse(ret)72 ####73 #æ¥è¯¢Products74 elif kind=='1':75 data = json.loads(recv['data'])76 print(data)77 ret = {}78 ret['data'] = []79 #æ¥è¯¢ææå¨åº80 if data[0] == None:81 online_list = Products.objects.filter(status=True)82 for ii in range(len(online_list)):83 ret['data'].append([online_list[ii].name,online_list[ii].numid,online_list[ii].cardid,\84 online_list[ii].price,online_list[ii].operator,status_dict[online_list[ii].status],\85 online_list[ii].addtime.strftime("%Y-%m-%d %H:%M:%S"),online_list[ii].outtime.strftime("%Y-%m-%d %H:%M:%S") if (online_list[ii].outtime!=None) else ("--")])86 #æ¥è¯¢æ个æµæ°´å·87 else:88 numid = data[0]89 #æ¾å°çå表90 online_list = Products.objects.filter(numid=numid)91 if len(online_list)==0:92 #没ææ¤å·93 ret['status'] = "nofind"94 else:95 for ii in range(len(online_list)):96 ret['data'].append([online_list[ii].name, online_list[ii].numid, online_list[ii].cardid, \97 online_list[ii].price, online_list[ii].operator, status_dict[online_list[ii].status], \98 online_list[ii].addtime.strftime("%Y-%m-%d %H:%M:%S"), online_list[ii].outtime.strftime("%Y-%m-%d %H:%M:%S") if (online_list[ii].outtime!=None) else ("--")])99 ret['status'] = "ok"100101 return JsonResponse(ret)102103 ###104 #æ¥è¯¢è®°å½105 elif kind=='2':106 data = json.loads(recv['data'])107 print(data)108 ret = {}109 ret['data'] = []110 all_list = AlertLog.objects.filter()111 for ii in range(len(all_list)):112 ret['data'].append([all_list[ii].productname,all_list[ii].productnumid,type_dict[all_list[ii].type],\113 all_list[ii].addtime.strftime("%Y-%m-%d %H:%M:%S"),all_list[ii].comments])114 ret['status'] = "ok"115116 return JsonResponse(ret)117118 # ä¸è½½æ°æ®119 elif kind == '3':120 ret = {}121 ret['data'] = []122123 all_list = AlertLog.objects.filter()124125 the_file_name = "temp.txt"126127 file_handle = open(the_file_name, mode='w')128 for ii in range(len(all_list)):129 temp_row = ([all_list[ii].productname, all_list[ii].productnumid, type_dict[all_list[ii].type], \130 all_list[ii].addtime.strftime("%Y-%m-%d %H:%M:%S"), all_list[ii].comments])131 file_handle.write(str(temp_row) + '\n')132 file_handle.close()133134 response = StreamingHttpResponse(file_iterator(the_file_name))135 response['Content-Type'] = 'application/octet-stream'136 response['Access-Control-Expose-Headers'] = 'Content-Disposition' # å
许跨å137 response['Content-Disposition'] = 'attachment;filename="temp.txt"'138 return response139140141 return JsonResponse(ret)142143##ä¸è½½æ件144def file_iterator(file_name, chunk_size=512):145 with open(file_name) as f:146 while True:147 c = f.read(chunk_size)148 if c:149 yield c150 else:151 break152
...
PlayerListAPI.py
Source:PlayerListAPI.py
1import re2import os3import yaml4from mcdreforged.api.all import *56PLUGIN_METADATA = {7 'id': 'player_list_api',8 'version': '0.1.1',9 'name': 'PlayerListAPI',10 'description': "A MCDR plugin for listing players and bots",11 'author': ['Youmiel'],12 'link': '',13 'dependencies': {14 'mcdreforged': '>=1.0.0',15 }16}1718online_list = [] # all player entities19bot_list = [] # bots2021PLAYER_PATTERN = re.compile(r'(\w+)\[([0-9\.:/]+|local|CarpetPlugin)\] logged in with entity id')22 # compatibility with CarpetPlugin by ishland (for paperspigot users)23CONFIG_PATH = os.path.join('config', 'PlayerListAPI.yml')2425default_config = {26 'tag_bots': False, # an option for datapacks27 'isCarpet': True, # false for player list only, true for carpet feature(CarpetPlugin too)28 'clean_logs': True # prevent /tag command feedback in logs29 }30config = default_config.copy()3132#-------API START-------3334def get_list_all():35 return online_list.copy()36 37def get_list_player():38 player_list = online_list.copy()39 for bot in bot_list:40 player_list.remove(bot)41 return player_list.copy()42 43def get_list_bot():44 return bot_list.copy()4546#--------API END--------4748def on_load(server: ServerInterface, old_module):49 #TODO: config, OOP(list)50 global online_list, bot_list51 if old_module and type(old_module.online_list) == type(online_list):52 online_list = old_module.online_list53 bot_list = old_module.bot_list54 load_config(server)5556def on_server_startup(server: ServerInterface):57 global online_list, bot_list58 online_list = []59 bot_list = []60 61def on_player_joined(server: ServerInterface, player, info):62 global online_list, bot_list63 online_list.append(player)64 if config['isCarpet']:65 botinfo = judge_bot(info.content)66 if botinfo[1] == 'bot' and player not in bot_list:67 bot_list.append(player)68 if config['tag_bots']:69 add_tag(server, player) 70 elif config['tag_bots'] and botinfo[1] == 'player':71 remove_tag(server, player)7273def on_player_left(server: ServerInterface, player):74 global online_list, bot_list75 online_list.remove(player)76 if player in bot_list:77 bot_list.remove(player)7879def load_config(server: ServerInterface):80 global config81 try:82 config = {}83 with open(CONFIG_PATH) as file: 84 conf_yaml = yaml.load(file, Loader=yaml.Loader) # idk why CLoader doesn't work85 for key in default_config.keys():86 config[key] = conf_yaml[key]87 server.logger.info('Config file loaded')88 except Exception as e: 89 server.logger.info('fail to read config file: %s using default config'%e)90 config = default_config.copy()91 with open(CONFIG_PATH, 'w') as file: 92 yaml.dump(default_config, file)93 9495def judge_bot(msg):96 global PLAYER_PATTERN97 joined_player = re.match(PLAYER_PATTERN, msg)98 if joined_player:99 if joined_player.group(2) == 'local':100 return [True, 'bot', joined_player.group(1)] # return [<isPlayer>,<type>,<name>]101 else:102 return [True, 'player', joined_player.group(1)]103 return [False, 'some_type', 'something']104105def add_tag(server:ServerInterface, bot):106 if config['clean_logs']:107 server.execute('execute as %s run tag @s[tag=!isBot] add isBot'%bot)108 else:109 server.execute('tag %s add isBot'%bot) # will produce one more line in log110 111def remove_tag(server:ServerInterface, bot):112 if config['clean_logs']:113 server.execute('execute as %s run tag @s[tag=isBot] remove isBot'%bot)114 else:115 server.execute('tag %s remove isBot'%bot) # will produce one more line in log116 117 118 '''119def on_info(server: ServerInterface, info): #debug use120 global online_list, bot_list121 if info.is_player and info.content == '!!list':122 send_list(server)123124@new_thread("send_list")125def send_list(server: ServerInterface): #debug use126 global online_list, bot_list127 server.logger.info("online_list: %s" % online_list)128 server.logger.info("bot_list: %s" % bot_list)129 player_list = online_list.copy()130 for bot in bot_list:131 player_list.remove(bot)132 server.logger.info("player_list: %s" % player_list)
...
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!!