Best Python code snippet using lemoncheesecake
server27.py
Source:server27.py
1# Ex. 2.7 template - server side2# Author: Barak Gonen, 20173# Modified for Python 3, 20204import glob5import shutil6import socket7import subprocess8import animation9import pyautogui10import protocol11import os.path12IP = "0.0.0.0"13# The path + filename where the screenshot at the server should be saved14# can use auto path getting for easy time15# PHOTO_PATH = str(pathlib.Path().resolve()) + r"server_screenshot.jpg"16PHOTO_PATH = r"D:\Coding\networks\NetworksExercises\adv_socket_ex_2.7" + r"\server_screenshot.jpg"17def __dir_response(param):18 is_successful = True19 try:20 notes = glob.glob(str(param[0]) + r"\*")21 except Exception as e:22 notes = str(e)23 is_successful = False24 return is_successful, notes25def __delete_response(param):26 is_successful = True27 notes = 'success!'28 try:29 os.remove(param[0])30 except Exception as e:31 notes = str(e)32 is_successful = False33 return is_successful, notes34def __copy_response(params):35 is_successful = True36 notes = 'success!'37 try:38 shutil.copy(params[0], params[1])39 except Exception as e:40 notes = str(e)41 is_successful = False42 return is_successful, notes43def __execute_response(param):44 is_successful = True45 notes = 'success!'46 try:47 subprocess.call(param)48 except Exception as e:49 notes = str(e)50 is_successful = False51 return is_successful, notes52def __take_screenshot_response(param):53 is_successful = True54 notes = 'success!'55 try:56 image = pyautogui.screenshot(PHOTO_PATH)57 image.save(PHOTO_PATH)58 except Exception as e:59 notes = str(e)60 print(f"there was an exception:\n{notes}")61 is_successful = False62 return is_successful, notes63def __send_photo_response(param):64 return os.path.isfile(PHOTO_PATH), str(os.path.getsize(PHOTO_PATH))65def __exit_response(param):66 return True, "exiting ..."67@animation.wait('spinner', text=f"sending image to client by chunks of {protocol.PHOTO_CHUNK_SIZE} ... ", speed=0.25)68def send_photo(client_socket: socket):69 """70 sends the server screenshot to the client's socket71 :param client_socket: the socket to send the photo to72 :return: nothing73 """74 # open the photo file75 photo_file = open(PHOTO_PATH, 'rb')76 # get a piece of the image77 photo_chunk = photo_file.read(protocol.PHOTO_CHUNK_SIZE)78 while photo_chunk:79 # send the piece of the image80 client_socket.send(photo_chunk)81 photo_chunk = photo_file.read(protocol.PHOTO_CHUNK_SIZE)82 photo_file.close()83# list the known commands, how many parameters they can get, and what function handles them84# map: {'COMMAND': (NUMBER_OF_PARAMETERS, FUNCTION_TO_HANDLE_COMMAND),...}85COMMANDS_RESPONSES = {'DIR': __dir_response, 'DELETE': __delete_response, 'COPY': __copy_response,86 'EXECUTE': __execute_response, 'TAKE_SCREENSHOT': __take_screenshot_response,87 'EXIT': __exit_response, 'SEND_PHOTO': __send_photo_response}88def check_client_request(cmd_data):89 """90 Break cmd to command and parameters91 Check if the command and params are good.92 For example, the filename to be copied actually exists93 Returns:94 valid: True/False95 command: The requested cmd (ex. "DIR")96 params: List of the cmd params (ex. ["c:\\cyber"])97 """98 # Use protocol.check_cmd first99 # protocol.check_cmd check that the command is one of the known commands,100 # and that they sent the correct number of parameters.101 protocol_check = protocol.check_cmd(cmd_data)102 is_request_valid = False103 cmd_with_params = cmd_data.split()104 # the first entry in the data is the command105 cmd = cmd_with_params[0]106 # the rest of the data is the command params107 params = cmd_with_params[1:]108 # Then make sure the params are valid109 # TODO: need to add else for every if and describe the error110 if protocol_check:111 """112 command #parameters type113 DIR: 1 Directory114 DELETE: 1 File/Directory115 COPY: 2 File/Directory, File/Directory116 EXECUTE: 1 File(.exe)117 TAKE_SCREENSHOT: 0118 EXIT: 0119 """120 if cmd in ('EXIT', 'TAKE_SCREENSHOT'):121 # commands with no parameters, the protocol check is enough122 is_request_valid = True123 elif cmd == 'SEND_PHOTO':124 if os.path.isfile(PHOTO_PATH):125 is_request_valid = True126 elif cmd == 'DIR':127 if os.path.isdir(params[0]):128 is_request_valid = True129 elif cmd == 'DELETE':130 if os.path.isdir(params[0]) or os.path.isfile(params[0]):131 is_request_valid = True132 elif cmd == 'EXECUTE':133 if os.path.isfile(params[0]) and params[0].endswith('.exe'):134 is_request_valid = True135 elif cmd == 'COPY':136 if os.path.isfile(params[0]) and not os.path.exists(params[1]):137 # the extension of the parameter is the last item in the array after splitting by '.'138 extension_from = params[0].split('.')[-1]139 extension_to = params[1].split('.')[-1]140 if extension_from == extension_to:141 is_request_valid = True142 # (6)143 return is_request_valid, cmd, params144def handle_client_request(command, params):145 """Create the response to the client, given the command is legal and params are OK146 For example, return the list of filenames in a directory147 Note: in case of SEND_PHOTO, only the length of the file will be sent148 Returns:149 is_successful: if the requested were successful150 response: the requested data151 """152 # (7)153 is_successful, notes = COMMANDS_RESPONSES[command](params)154 return is_successful, notes155def main():156 # open socket with client157 server_socket = socket.socket()158 server_socket.bind((IP, protocol.PORT))159 server_socket.listen()160 print("Server is up and running")161 wait_animation = animation.Wait('spinner', text="waiting for a client to connect ... ", speed=0.25)162 wait_animation.start()163 (client_socket, client_address) = server_socket.accept()164 wait_animation.stop()165 print("Client connected")166 # (1)167 # handle requests until user asks to exit168 while True:169 # Check if protocol is OK, e.g. length field OK170 valid_protocol, cmd = protocol.get_msg(client_socket)171 print("message received from client.")172 if valid_protocol:173 print("client returned a valid response.\nchecking if: '" + cmd + "' is a valid command...")174 # Check if params are good, e.g. correct number of params, file name exists175 valid_cmd, command, params = check_client_request(cmd)176 if valid_cmd:177 print("command is valid, creating response...")178 # (6)179 # prepare a response using "handle_client_request"180 is_command_successful, response = handle_client_request(command, params)181 # add length field using "create_msg"182 msg = protocol.create_msg(str(response))183 # send to client184 client_socket.send(msg)185 if command == 'SEND_PHOTO':186 if is_command_successful:187 # Send the data itself to the client188 send_photo(client_socket)189 else:190 response = "something went wrong with sending the photo. this should not happen"191 print(response)192 # (9)193 if command == 'EXIT':194 break195 else:196 # prepare proper error to client197 is_command_successful = False198 response = 'Bad command or parameters'199 print(response)200 # send to client201 else:202 # prepare proper error to client203 is_command_successful = False204 response = 'Packet not according to protocol'205 print(response)206 # send to client207 # Attempt to clean garbage from socket208 # client_socket.recv(1024)209 if not is_command_successful:210 client_socket.send(protocol.create_msg(response))211 # close sockets212 print("Closing connection")213if __name__ == '__main__':...
app.py
Source:app.py
1from flask import Flask, request, jsonify2from flask_cors import CORS3from pysondb import db4app = Flask(__name__)5CORS(app, resources={r"/*":{'origins':"*"}})6database = db.getDb("./database.json")7@app.route("/", methods=["GET", "POST"])8def api():9 if request.method == "POST":10 incoming_data = request.get_json()11 title = incoming_data["title"]12 desc = incoming_data["desc"]13 is_completed = incoming_data["completed"]14 database.add({"title": title, "desc": desc, "completed": is_completed})15 # Since Python and JS handle large numbers differently. Therefore, trim down the id to just 6 digits so its the same on both16 task_id = database.getByQuery({"title": title})[0]["id"]17 database.updateByQuery({"title": title}, {"id": int(str(task_id)[:6])})18 return jsonify(database.getAll())19@app.route("/delete", methods=["GET", "POST"])20def delete_task():21 is_successful = False22 if request.method == "POST":23 incoming_data = request.get_json()24 task_to_delete = incoming_data["id"]25 database.deleteById(task_to_delete)26 is_successful = True27 return jsonify({"deleted": is_successful})28@app.route("/complete", methods=["POST"])29def complete_task():30 incoming_data = request.get_json()31 id = incoming_data["id"]32 task = database.getByQuery({"id": id})[0]33 database.updateByQuery({"id": id}, 34 {"completed": not task["completed"]})35 is_successful = True36 return jsonify({"update": is_successful})37@app.route("/update", methods=["GET", "POST"])38def update_task():39 is_successful = False40 if request.method == "POST":41 incoming_data = request.get_json()42 id_to_update = incoming_data["id"]43 new_title = incoming_data["title"]44 new_desc = incoming_data["desc"]45 is_completed = incoming_data["completed"]46 database.updateByQuery({"id": id_to_update}, 47 {"title": new_title, 48 "desc": new_desc, 49 "completed": is_completed}50 )51 is_successful = True52 return jsonify({"update": is_successful})53if __name__ == "__main__":...
bulk_enrollment_operation_result.py
Source:bulk_enrollment_operation_result.py
1# coding=utf-82# --------------------------------------------------------------------------3# Code generated by Microsoft (R) AutoRest Code Generator.4# Changes may cause incorrect behavior and will be lost if the code is5# regenerated.6# --------------------------------------------------------------------------7from msrest.serialization import Model8class BulkEnrollmentOperationResult(Model):9 """Bulk enrollment operation result.10 :param is_successful: Indicates if the operation was successful in its11 entirety12 :type is_successful: bool13 :param errors: Registration errors14 :type errors: list[~serviceswagger.models.BulkEnrollmentOperationError]15 """16 _validation = {17 'is_successful': {'required': True},18 }19 _attribute_map = {20 'is_successful': {'key': 'isSuccessful', 'type': 'bool'},21 'errors': {'key': 'errors', 'type': '[BulkEnrollmentOperationError]'},22 }23 def __init__(self, is_successful, errors=None):24 self.is_successful = is_successful...
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!!