<commit_before>from zrest.statuscodes import *
from http.server import BaseHTTPRequestHandler, HTTPServer
from .basedatamodel import RestfulBaseInterface
from .statuscodes import *
from zashel.utils import threadize
from urllib.parse import urlparse, parse_qsl
from math import ceil
import re
import json
import ssl
import os

GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
DELETE = "DELETE"
ALL = [GET,
       POST,
       PUT,
       PATCH,
       DELETE]

def not_implemented(*args, **kwargs):
    """
    Base function for not implemented methods. Default method for every model
    assigned to app.
    :retrurns: an str jsonify object: {"Error": "501"}
    
    """
    return json.dumps({"Error": "501"})

class Handler(BaseHTTPRequestHandler):
    """
    Base Handler for ZRest APP. It can be subclassed to implement exceptions
    to any thing. Subclassing is imperative wheather multiple apps are ins-
    tantiated and each of them have a different behavour.
    
    It has the following methods:
    :method _prepare: private method to prepare and send the reponse to
                      client. It sends a 404 - Not d Error in case there 
                      is no data found.
    :method set_app: class method to assign the app to the handler. Used
                     the time the app is instantiated.
    :method do_GET: calls _prepare with no other parameter than a GET action.
    :method do_POST: calls _prepare with POST action and 201 response as 
                     default.
    :method do_PUT: calls _prepare with no other parameter than a PUT action.
    :method do_PATCH: calls _prepare with no other paramenter than a PATCH action.
    :method do_DELETE: calls _prepare with no other paramenter than a DELETE action.
    
    """
    @property
    def rest_app(self):
        """
        Returns app assigned to Handler
        
        """
        return self._rest_app

    @classmethod
    def set_app(cls, app):
        """
        Defienes the app assigned to the handler. As a class method, if several
        apps has to be defined, a subclass of Handler for each one is needed.
        
        """
        cls._rest_app = app

    def _prepare(self, action, response_default=200):
        """
        Prepares and sends requested data to client.
        """
        if action in (POST, PUT, PATCH):
            data = self.rfile.read(int(self.headers["Content-Length"]))
            data = data.decode("utf-8") #To be changed
            data = self.rest_app.action(action, self.path, data=data)
        else:
            data = self.rest_app.action(action, self.path)
        response = data["response"]
        if response == 0:
            response = response_default
        if not data["payload"] and action == GET:
            response = 404
        self.send_response(response, get_code(response).text)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        headers =  self.rest_app.headers.copy()
        headers.update(data["headers"])
        for header in headers:
            self.send_header(header, headers[header])
        self.end_headers()
        if data["payload"]:
            self.wfile.write(bytearray(json.dumps(data["payload"]), "utf-8"))

    def do_GET(self):
        self._prepare(GET)
        return

    def do_POST(self):
        self._prepare(POST, 201)
        return

    def do_PUT(self):
        self._prepare(PUT)
        return

    def do_PATCH(self):
        self._prepare(PATCH)
        return

    def do_DELETE(self):
        self._prepare(DELETE)<commit_msg>Documenting<commit_after>from zrest.statuscodes import *
from http.server import BaseHTTPRequestHandler, HTTPServer
from .basedatamodel import RestfulBaseInterface
from .statuscodes import *
from zashel.utils import threadize
from urllib.parse import urlparse, parse_qsl
from math import ceil
import re
import json
import ssl
import os

GET = "GET"
POST = "POST"
PUT = "PUT"
PATCH = "PATCH"
DELETE = "DELETE"
ALL = [GET,
       POST,
       PUT,
       PATCH,
       DELETE]

def not_implemented(*args, **kwargs):
    """
    Base function for not implemented methods. Default method for every model
    assigned to app.
    :retrurns: an str jsonify object: {"Error": "501"}
    
    """
    return json.dumps({"Error": "501"})

class Handler(BaseHTTPRequestHandler):
    """
    Base Handler for ZRest APP. It can be subclassed to implement exceptions
    to any thing. Subclassing is imperative wheather multiple apps are ins-
    tantiated and each of them have a different behavour.
    
    It has the following methods:
    :method _prepare: private method to prepare and send the reponse to
                      client. It sends a 404 - Not d Error in case there 
                      is no data found.
    :method set_app: class method to assign the app to the handler. Used
                     the time the app is instantiated.
    :method do_GET: calls _prepare with no other parameter than a GET action.
    :method do_POST: calls _prepare with POST action and 201 response as 
                     default.
    :method do_PUT: calls _prepare with no other parameter than a PUT action.
    :method do_PATCH: calls _prepare with no other paramenter than a PATCH action.
    :method do_DELETE: calls _prepare with no other paramenter than a DELETE action.
    
    """
    @property
    def rest_app(self):
        """
        Returns app assigned to Handler
        
        """
        return self._rest_app

    @classmethod
    def set_app(cls, app):
        """
        Defienes the app assigned to the handler. As a class method, if several
        apps has to be defined, a subclass of Handler for each one is needed.
        
        """
        cls._rest_app = app

    def _prepare(self, action, response_default=200):
        """
        Prepares and sends requested data to client.
        :param action: Action to response. It may be one of predefined:
                       GET, PUT, POST, PATCH, DELETE
        :param response_default: Response code by default in case everything
                                 goes alright. 200 - OK by default. 
        
        """
        if action in (POST, PUT, PATCH):
            data = self.rfile.read(int(self.headers["Content-Length"]))
            data = data.decode("utf-8") #To be changed
            data = self.rest_app.action(action, self.path, data=data)
        else:
            data = self.rest_app.action(action, self.path)
        response = data["response"]
        if response == 0:
            response = response_default
        if not data["payload"] and action == GET:
            response = 404
        self.send_response(response, get_code(response).text)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        headers =  self.rest_app.headers.copy()
        headers.update(data["headers"])
        for header in headers:
            self.send_header(header, headers[header])
        self.end_headers()
        if data["payload"]:
            self.wfile.write(bytearray(json.dumps(data["payload"]), "utf-8"))

    def do_GET(self):
        """
        What to do with a GET query. Calls _prepare with a GET action. It can be
        overriden to change behavour.
        
        """
        self._prepare(GET)
        return

    def do_POST(self):
        """
        What to do with a POST query. Calls _prepare with a POST action and a 
        default response of 201 - Created. It can be overriden to change behavour.
        
        """
        self._prepare(POST, 201)
        return

    def do_PUT(self):
        """
        What to do with a PUT query. Calls _prepare with a PUT action. It can be
        overriden to change behavour.
        
        """
        self._prepare(PUT)
        return

    def do_PATCH(self):
        """
        What to do with a PATCH query. Calls _prepare with a PATCH action. It can be
        overriden to change behavour.
        
        """
        self._prepare(PATCH)
        return

    def do_DELETE(self):
        """
        What to do with a DELETE query. Calls _prepare with a DELETE action. It can be
        overriden to change behavour.
        
        """
        self._prepare(DELETE)
{'fraction_non_alphanumeric': 0.08106143220647037, 'fraction_numerical': 0.006785411365564037, 'mean_word_length': 2.1588212782242633, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '605254', 'n_tokens_mistral': 2354, 'n_tokens_neox': 2241, 'n_words': 839}