def __init__(self, *args, **kwargs): super(TwoFilesPerNodeLayout, self).__init__(*args, **kwargs) self.fwddefs_filename = self.backendConfig.get("FWDDEFS_OUTPUT", DEFAULT_FWDDEFS_OUTPUT) self.public_filename = self.backendConfig.get("PUBLIC_OUTPUT", DEFAULT_PUBLIC_OUTPUT) self.enums_filename = self.backendConfig.get("ENUMS_OUTPUT", DEFAULT_ENUMS_OUTPUT) self.fwddefs_template_path = self.backendConfig.get( "FWDDEFS_TEMPLATE") or DEFAULT_FWDDEFS_TEMPLATE self.public_template_path = self.backendConfig.get( "PUBLIC_TEMPLATE") or DEFAULT_PUBLIC_TEMPLATE self.enums_template_path = self.backendConfig.get( "ENUMS_TEMPLATE") or DEFAULT_ENUMS_TEMPLATE self.fwddefs_template = utils.load_template(self.fwddefs_template_path) self.public_template = utils.load_template(self.public_template_path) self.enums_template = utils.load_template(self.enums_template_path) self.nodeHeader_template_path = self.backendConfig.get( "NODE_HEADER_TEMPLATE", DEFAULT_TWOFILES_PER_NODE_HEADER_TEMPLATE) self.nodeImpl_template_path = self.backendConfig.get( "IMPL_TEMPLATE", DEFAULT_TWOFILES_PER_NODE_IMPL_TEMPLATE) self.node_header_template = utils.load_template( self.nodeHeader_template_path) self.node_impl_template = utils.load_template( self.nodeImpl_template_path)
def index(request): notes_list = db.get_all() # A string de request sempre começa com o tipo da requisição (ex: GET, POST) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] if verify_and_delete(corpo, db): return build_response(code=303, reason='See Other', headers='Location: /') note = get_note_from_post(corpo) if note.id == 'None': db.add(note) else: db.update(note) return build_response(code=303, reason='See Other', headers='Location: /') note_template = load_template('components/note.html') notes_li = [ note_template.format( title=dados.title, details=dados.content, id=dados.id) for dados in notes_list ] notes = '\n'.join(notes_li) return build_response() + load_template('index.html').format(notes=notes).encode()
def index(request, db): # A string de request sempre começa com o tipo da requisição (ex: GET, POST) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params = {} p1 = partes[1] # Preencha o dicionário params com as informações do corpo da requisição # O dicionário conterá dois valores, o título e a descrição. # Posteriormente pode ser interessante criar uma função que recebe a # requisição e devolve os parâmetros para desacoplar esta lógica. # Dica: use o método split da string e a função unquote_plus print('p1', p1) if (p1.startswith('id')): idd = p1[3:] db.delete(idd) elif (p1.startswith('update')): newNote = {} for chave_valor in p1.split('&'): if 'titulo' in chave_valor: titulo = chave_valor[7:] titulo = urllib.parse.unquote_plus(titulo) newNote['title'] = titulo elif 'id' in chave_valor: aiD = chave_valor[3:] newNote['id'] = aiD elif 'detalhes' in chave_valor: detalhes = chave_valor[9:] detalhes = urllib.parse.unquote_plus(detalhes) newNote['content'] = detalhes db.update(titulo, detalhes, aiD) else: for chave_valor in corpo.split('&'): if 'titulo' in chave_valor: titulo = chave_valor[7:] titulo = urllib.parse.unquote_plus(titulo) params['titulo'] = titulo elif 'detalhes' in chave_valor: detalhes = chave_valor[9:] detalhes = urllib.parse.unquote_plus(detalhes) params['detalhes'] = detalhes note = Note(title=params['titulo'], content=params['detalhes']) db.add(note) # O RESTO DO CÓDIGO DA FUNÇÃO index CONTINUA DAQUI PARA BAIXO.. note_template = load_template('components/note.html') notes_li = [ note_template.format(id=dados.id, title=dados.title, details=dados.content) for dados in load_data(db) ] notes = '\n'.join(notes_li) return load_template('index.html').format(notes=notes).encode()
def index(*args, **kwargs): db = create_connection() cursor = db.cursor() cursor.execute(select_all_categories) result = cursor.fetchall() cursor.close() box_string = "" for item in result: box_string += "<input id=\"{0}\" type=\"checkbox\" name=\"checkbox\" " \ "value=\"{1}\"/> <label for=\"{2}\">{3}</label><br />".format(item[0], item[1], item[0], item[1]) sidebar_form = "\n <form name=\"search\" action=\"\" method=\"POST\">\n" \ " Search query\n <input type=\"text\" name=\"search_query\"></br>\n" \ " Initial category\n <div style=\"height: 6em; width: 12em; overflow: auto;\">\n" \ " {0}\n </div>\n <input type=\"submit\" value=\"Submit\"/>\n " \ "</form>\n ".format(box_string) template = load_template('index') + sidebar_form + load_template('search_result') if 'search_result' in kwargs: content_string = "<ul class=\"search_result\">" for item in kwargs['search_result']: content_string = content_string + "<li>" + item[0] + " " + str(item[1]) + "</li>" content_string += "</ul>" template += "<p>Search result for :" + kwargs['query'] + "</p>" + content_string + load_template('footer') elif 'message' in kwargs: template += kwargs['message'] + load_template('footer') else: template += load_template('footer') return template
def save_product(*args, **kwargs): try: prod_name = kwargs['query_string'].get('product_name')[0] prod_price = kwargs['query_string'].get('product_price')[0] init_cat = kwargs['query_string'].get('init_cat')[0] except TypeError: return load_template('admin_header') + "Please enter a valid name and price." + load_template('footer') db = create_connection() cursor = db.cursor() try: cursor.execute(insert_product(str(prod_name), float(prod_price), str(init_cat))) db.commit() except ValueError: db.rollback() template = load_template('admin_header') + "VALUE ERROR" + load_template('footer') return template except db.Error as e: print "Error code %s" % e.errno db.rollback() cursor.close() db.close() template = load_template('admin_header') + load_template('footer') return template
def view_products_cat(*args, **kwargs): product_name = kwargs['query_string'].get('name')[0] db = create_connection() cursor = db.cursor() cursor.execute(sql_categories_for_product(product_name)) result = cursor.fetchall() cursor.close() cat_for_prod = "" excluded_cats = [] for item in result: cat_for_prod += "<option selected=\"selected\">" + item[0] + "</option>" excluded_cats.append(item[0]) cursor = db.cursor() cursor.execute(sql_rest_of_cats(excluded_cats)) result = cursor.fetchall() cursor.close() other_cats = "" for item in result: other_cats += "<option>" + item[0] + "</option>" form = "<form name=\"add_prod\" action=\"/admin/add_categories_to_product\" method=\"POST\">" \ "<table style=\"width: 100%\" cellpadding=\"3\" cellspacing=\"0\"><tr><td style=\"width:33%\">" \ "Categories <select multiple size=\"8\" name=\"init_cat\">{0}</select> </td>" \ "<td align=\"center\" style=\"width:33%\"><input type=\"Button\" value=\">>\" onClick=\"SelectMoveRows(document.add_prod.init_cat, document.add_prod.other_cat)\"><br>" \ "<input type=\"Button\" value=\"<<\" onClick=\"SelectMoveRows(document.add_prod.other_cat, document.add_prod.init_cat)\"></td>" \ "<td style=\"width:33%\">Other categories <select size=\"8\" multiple name=\"other_cat\">{1}</select></td></tr></table>" \ "<input type=\"submit\" value=\"Save\">" \ "<input type=\"hidden\" value=\"{2}\" name=\"prod_name\"\></form>".format(cat_for_prod, other_cats, product_name) template = load_template('admin_header') + "Product :" + product_name + form + load_template('footer') return template
def __init__(self, *args, **kwargs): super(TwoFilesLayout, self).__init__(*args, **kwargs) self.header_filename = self.backendConfig.get("HEADER_OUTPUT") or None self.impl_filename = self.backendConfig.get("IMPL_OUTPUT") or None assert self.header_filename is not None, "HEADER_OUTPUT variable MUST be specified in the backend config. This is the file to the generated header code for all nodes will be written to." assert self.impl_filename is not None, "IMPL_OUTPUT variable MUST be specified in the backend config. This is the file to the generated impl code for all nodes will be written to." self.header_template_path = self.backendConfig.get("HEADER_TEMPLATE") or DEFAULT_TWOFILES_HEADER_TEMPLATE self.impl_template_path = self.backendConfig.get("IMPL_TEMPLATE") or DEFAULT_TWOFILES_IMPL_TEMPLATE self.header_template = utils.load_template(self.header_template_path) self.impl_template = utils.load_template(self.impl_template_path)
def index(request): # Cria uma lista de <li>'s para cada anotação # Se tiver curiosidade: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions # A string de request sempre começa com o tipo da requisição (ex: GET, POST) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params = {} # Preencha o dicionário params com as informações do corpo da requisição # O dicionário conterá dois valores, o título e a descrição. # Posteriormente pode ser interessante criar uma função que recebe a # requisição e devolve os parâmetros para desacoplar esta lógica. # Dica: use o método split da string e a função unquote_plus for chave_valor in corpo.split('&'): chave_valor = unquote_plus(chave_valor) split2 = chave_valor.split('=') params[split2[0]] = split2[1] note = Note() note.title = params['titulo'] note.content = params['detalhes'] if "update" in params.keys(): note.id = params["update"] db.update(note) print(params["update"]) print(id) elif "delete" in params.keys(): db.delete(params["delete"]) else: db.add(note) return build_response(code=303, reason='See Other', headers='Location: /') elif request.startswith('GET'): note_template = load_template('components/note.html') notes_li = [ note_template.format(title=note.title, details=note.content, id=note.id) for note in db.get_all() ] notes = '\n'.join(notes_li) return build_response(load_template('index.html').format(notes=notes))
def view_category(*args, **kwargs): string = "<ul>" db = create_connection() connection = db.cursor() connection.execute(select_all_categories) result = connection.fetchall() connection.close() for item in result: string += "<li><a href=\"/admin/view_category?id={0}\">{1}</a></li>".format(item[0], item[1]) string += "</ul> \n" template = load_template('admin_header') + string + load_template('footer') return template
def __init__(self, *args, **kwargs): super(TwoFilesLayout, self).__init__(*args, **kwargs) self.header_filename = self.backendConfig.get("HEADER_OUTPUT") or None self.impl_filename = self.backendConfig.get("IMPL_OUTPUT") or None assert self.header_filename is not None, "HEADER_OUTPUT variable MUST be specified in the backend config. This is the file to the generated header code for all nodes will be written to." assert self.impl_filename is not None, "IMPL_OUTPUT variable MUST be specified in the backend config. This is the file to the generated impl code for all nodes will be written to." self.header_template_path = self.backendConfig.get( "HEADER_TEMPLATE") or DEFAULT_TWOFILES_HEADER_TEMPLATE self.impl_template_path = self.backendConfig.get( "IMPL_TEMPLATE") or DEFAULT_TWOFILES_IMPL_TEMPLATE self.header_template = utils.load_template(self.header_template_path) self.impl_template = utils.load_template(self.impl_template_path)
def index(request): note_template = load_template('components/note.html') # A string de request sempre começa com o tipo da requisição (ex: GET, POST) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params = {} # Preencha o dicionário params com as informações do corpo da requisição # O dicionário conterá dois valores, o título e a descrição. # Posteriormente pode ser interessante criar uma função que recebe a # requisição e devolve os parâmetros para desacoplar esta lógica. # Dica: use o método split da string e a função unquote_plus for chave_valor in corpo.split('&'): # AQUI É COM VOCÊ unquote = urllib.parse.unquote_plus(chave_valor).split('=') params[unquote[0]] = unquote[1] print('\n----------PARAMS -------------') print(params) print('\n-------------------------------') with open('data/notes.json') as json_file: data = json.load(json_file) data.append(params) write_json(data) return build_response(code=303, reason='See Other', headers='Location: /') else: # Cria uma lista de <li>'s para cada anotação # Se tiver curiosidade: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions notes_li = [ note_template.format(title=dados['titulo'], details=dados['detalhes']) for dados in load_data('notes.json') ] notes = '\n'.join(notes_li) return build_response() + load_template('index.html').format( notes=notes).encode()
def service(self, request): response = HttpResponse() response.set_header("Connection", "close") response.set_contents( utils.load_template("index.html", self.templates_dir)) response.set_attribute("title", "Home python server") return response
def __init__(self, *args, **kwargs): super(OneFileLayout, self).__init__(*args, **kwargs) self.outfileName = self.backendConfig.get("HEADER_OUTPUT") or None assert self.outfileName is not None, "HEADER_OUTPUT variable MUST be specified in the backend config. This is the file to the generated code for all nodes will be written to." self.templateName = self.backendConfig.get( "HEADER_TEMPLATE") or DEFAULT_ONEFILE_TEMPLATE self.template = utils.load_template(self.templateName)
def show_info(start_response): file_name = TEMPLATES_ROOT + '/info.html' return load_template(file_name, start_response, name='王五', age=34, gender='男')
def service(self, request): response = HttpResponse() response.set_contents(utils.load_template("media.html", self.templates_dir)) MEDIA_DIR = MUSIC_FILES_DIR if request.get_requested_page().startswith("/music") else VIDEO_FILES_DIR media_type = "music" if MEDIA_DIR == MUSIC_FILES_DIR else "video" search_pattern = "^.*\.(mp3|wma|wav|)$" if media_type == "music" else "^.*\.(avi|flv|wmv|)$" file_names = {"dirs": [], "files": []} # getting requested sub-folder subdir = request.get_request_param("folder") if subdir is not None: subdir = urlparse.unquote(subdir, "utf-8") media_dir = os.path.join(MEDIA_DIR, subdir) else: media_dir = MEDIA_DIR subdir = "" # listing files, names of that will be sent to client files = [] try: files = os.listdir(media_dir) except FileNotFoundError as err: print("Directory wasn't found") for file in files: if re.match(search_pattern, file): file_names["files"].append([subdir, file]) elif os.path.isdir(os.path.join(media_dir, file)): file_names["dirs"].append([subdir, file]) files_list = "" if media_dir != MEDIA_DIR and media_dir[:-1] != MEDIA_DIR: parent_folder = os.path.dirname(media_dir) print("PARENT: " + parent_folder) if parent_folder != MEDIA_DIR: link = "{1}?folder={0}".format(parent_folder[len(MEDIA_DIR) + 1:], media_type) else: link = media_type files_list += "<div><a href=\"{0}\"><span class=\"folder\">{1}</span></a></div>\r\n"\ .format(link, "...") for folder in sorted(file_names["dirs"]): files_list += "<div><a href=\"{2}?folder={0}\"><span class=\"folder\">{1}</span></a>" \ "<span class=\"play-btn\" onclick=\"playFolder('{2}', '{0}')\">" \ "Play</span></div>\r\n"\ .format(os.path.join(folder[0], folder[1]), folder[1], media_type) for file in sorted(file_names["files"]): files_list += "<div onclick=\"playTrack('{2}', '{1}')\">{0}</div>\r\n".format(file[1], re.sub("'", "\\'", os.path.join(file[0], file[1])), media_type) response.set_attribute("files", files_list) now_playing = "" if "player" in self.context.keys() and self.context["player"] is not None: now_playing = self.context["player"].get_current_file() if now_playing is not None and not now_playing == "": splitted = now_playing.split("/") if splitted is not None and len(splitted) > 0: now_playing = splitted[-1] else: now_playing = "" response.set_attribute("now_playing", now_playing) title = "Video" if media_type == "video" else "Music" title += "" if subdir == "" else ": " + subdir response.set_attribute("title", title) return response
def save_category(*args, **kwargs): cat = kwargs['query_string'].get('category') db = create_connection() cursor = db.cursor() try: cursor.execute(insert_category(str(cat[0]))) db.commit() except db.Error: db.rollback() except TypeError: return load_template('admin_header') + "Enter a vaild name." + load_template('footer') cursor.close() db.close() template = load_template('admin_header') + load_template('footer') return template
def show_info(start_response): file_name = TEMPLATES_ROOT + '/info.html' # return load_template(file_name, start_response, **{"name": '李四', 'age': 23, 'gender': '男'}) return load_template(file_name, start_response, name='王五', age=34, gender='男')
def __init__(self, *args, **kwargs): super(TwoFilesPerNodeLayout, self).__init__(*args, **kwargs) self.fwddefs_filename = self.backendConfig.get("FWDDEFS_OUTPUT", DEFAULT_FWDDEFS_OUTPUT) self.public_filename = self.backendConfig.get("PUBLIC_OUTPUT", DEFAULT_PUBLIC_OUTPUT) self.enums_filename = self.backendConfig.get("ENUMS_OUTPUT", DEFAULT_ENUMS_OUTPUT) self.fwddefs_template_path = self.backendConfig.get("FWDDEFS_TEMPLATE") or DEFAULT_FWDDEFS_TEMPLATE self.public_template_path = self.backendConfig.get("PUBLIC_TEMPLATE") or DEFAULT_PUBLIC_TEMPLATE self.enums_template_path = self.backendConfig.get("ENUMS_TEMPLATE") or DEFAULT_ENUMS_TEMPLATE self.fwddefs_template = utils.load_template(self.fwddefs_template_path) self.public_template = utils.load_template(self.public_template_path) self.enums_template = utils.load_template(self.enums_template_path) self.nodeHeader_template_path = self.backendConfig.get("NODE_HEADER_TEMPLATE", DEFAULT_TWOFILES_PER_NODE_HEADER_TEMPLATE) self.nodeImpl_template_path = self.backendConfig.get("IMPL_TEMPLATE", DEFAULT_TWOFILES_PER_NODE_IMPL_TEMPLATE) self.node_header_template = utils.load_template(self.nodeHeader_template_path) self.node_impl_template = utils.load_template(self.nodeImpl_template_path)
def index(request): if request.startswith('POST'): request = request.replace('\r', '') partes = request.split('\n\n') corpo = partes[1] params = {} for chave_valor in corpo.split('&'): splitted = chave_valor.split('=') params[splitted[0]] = splitted[1].replace('+', ' ') if params['type'] == 'create': add_entry(params) elif params['type'] == 'edit': notes = load_data() note_to_send = list() for note in notes: if note.title == params[ 'org_title'] and note.content == params['org_content']: note_to_send.extend( [note.id, params['titulo'], params['detalhes']]) break update_database(note_to_send) elif params['type'] == 'delete': notes = load_data() id = None for note in notes: if note.title == params[ 'org_title'] and note.content == params['org_content']: id = note.id break delete_from_database(id) return build_response(code=303, reason='See Other', headers='Location: /') note_template = load_template('components/note.html') notes_li = [ note_template.format(title=note.title, details=note.content) for note in load_data() ] notes = '\n'.join(notes_li) return build_response(load_template('index.html').format(notes=notes))
def index(request): note_template = load_template('components/note.html') # A string de request sempre começa com o tipo da requisição (ex: GET, POST) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] print("Corpo = {}".format(corpo)) note = post_into_note(corpo) if note is None: print("Entroooooooooooooooooooooooooooooou") return build_response(code=303, reason='See Other', headers='Location: /') else: if note.id == 'None': db.add(note) else: db.update(note) # Importante para editar e ecluir uma nota return build_response(code=303, reason='See Other', headers='Location: /') else: all_notes = db.get_all() # Cria uma lista de <li>'s para cada anotação # Se tiver curiosidade: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions notes_li = [ note_template.format(id=dados.id, title=dados.title, details=dados.content) for dados in all_notes ] notes = '\n'.join(notes_li) return build_response() + load_template('index.html').format( notes=notes).encode(encoding='utf-8')
def edit(request, db): if request.startswith('POST'): request = request.replace('\r', '') partes = request.split('\n\n') corpo = partes[1] params = {} print('corpo', corpo) idRaw = corpo.split('&')[1] id = idRaw[3:] noteEditTemplate = load_template('components/noteEdit.html') note = db.get_one(id) for n in note: [iddd, tituloo, contentt] = n notes = noteEditTemplate.format(id=iddd, title=tituloo, detalhes=contentt) return load_template('edit.html').format(noteEdit=notes).encode()
def index(request): db = Database('banco-notes') if request.startswith('POST'): params = save_params( request ) #params = {'titulo':algm coisa, 'detalhes':outra coisa, 'id':outra coisa} #add_to_jsonfile(params, 'notes.json') if 'deletar' in params.keys(): db.delete(params['deletar']) #id elif params['id'] == 'None': db.add( Note(title=params['titulo'], content=params['detalhes'], id=params['id'])) else: db.update( Note(title=params['titulo'], content=params['detalhes'], id=params['id'])) return build_response(code=303, reason='See Other', headers='Location: /') else: # Cria uma lista de <li>'s para cada anotação print('notas do banco: ', db.get_all()) note_template = load_template('components/note.html') notes_li = [ note_template.format(id=note.id, title=note.title, details=note.content) for note in db.get_all() ] notes = '\n'.join(notes_li) print('----------------------------------------') return build_response(load_template('index.html').format(notes=notes))
def service(self, request): """Default behaviour is to send response with 404 error code""" response = HttpResponse() response.set_response_code(404) response.set_response_status("Not found") response.set_attribute("error_code", response.http_code) response.set_attribute("status", response.response_status) response.set_attribute("message", "Requested page <span class=\"page\">{0}</span> was not found." .format(request.get_header("Host") + request.get_requested_resource())) response.set_contents(utils.load_template("error_page.html")) return response
def add_product(*args, **kwargs): db = create_connection() cursor = db.cursor() cursor.execute(select_all_categories) result = cursor.fetchall() cursor.close() db.close() string = "" for item in result: string += "<option>" + item[1] + "</option>" add_product_form = "<form name=\"add_prod\" action=\"/admin/add_product\" method=\"POST\">" \ "Product name : <input type=\"text\" name=\"product_name\"></br>" \ "Product price : <input type=\"text\" name=\"product_price\"></br>" \ "Initial category : <select name=\"init_cat\">{0}</select>" \ "<input type=\"submit\" value=\"Submit\"></form>".format(string) template = load_template('admin_header') + \ add_product_form + \ load_template('footer') return template
def index(request): # A string de request sempre começa com o tipo da requisição (ex: GET, POST) print(request) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] print(corpo) params = {} # Preencha o dicionário params com as informações do corpo da requisição # O dicionário conterá dois valores, o título e a descrição. # Posteriormente pode ser interessante criar uma função que recebe a # requisição e devolve os parâmetros para desacoplar esta lógica. # Dica: use o método split da string e a função unquote_plus for chave_valor in corpo.split('&'): print(chave_valor) split_chave_valor = chave_valor.split('=') split_novo1 = urllib.parse.unquote_plus(split_chave_valor[0]) split_novo2 = urllib.parse.unquote_plus(split_chave_valor[1]) params[split_novo1] = split_novo2 add_to_json(params, "notes.json") return build_response(code=303, reason='See Other', headers='Location: /') '''elif request.startswith('DELETE'): remove_from_json()''' # Cria uma lista de <li>'s para cada anotação # Se tiver curiosidade: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions note_template = load_template('components/note.html') notes_li = [ note_template.format(title=dados['titulo'], details=dados['detalhes'], id=dados['id']) for dados in load_data('notes.json') ] notes = '\n'.join(notes_li) return build_response(load_template('index.html').format(notes=notes))
def index(request): # A string de request sempre começa com o tipo da requisição (ex: GET, POST) if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params = {} # Preencha o dicionário params com as informações do corpo da requisição # O dicionário conterá dois valores, o título e a descrição. # Posteriormente pode ser interessante criar uma função que recebe a # requisição e devolve os parâmetros para desacoplar esta lógica. # Dica: use o método split da string e a função unquote_plus for chave_valor in corpo.split('&'): split = chave_valor.split('=') key = unquote_plus(split[0]) value = unquote_plus(split[1]) params[key] = value add_annotation(params) return build_response(code=303, reason='See Other', headers='Location: /') # return build_response(code='303',reason='See Other', headers='Location: /') # return 'HTTP/1.1 303 See Other Location: /\n\nHello World' # Cria uma lista de <li>'s para cada anotação # Se tiver curiosidade: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions note_template = load_template('components/note.html') notes_li = [ note_template.format(title=dados['titulo'], details=dados['detalhes']) for dados in load_data('notes.json') ] notes = '\n'.join(notes_li) return build_response() + load_template('index.html').format( notes=notes).encode()
def service(self, request): """Default behaviour is to send response with 404 error code""" response = HttpResponse() response.set_response_code(404) response.set_response_status("Not found") response.set_attribute("error_code", response.http_code) response.set_attribute("status", response.response_status) response.set_attribute( "message", "Requested page <span class=\"page\">{0}</span> was not found.". format( request.get_header("Host") + request.get_requested_resource())) response.set_contents(utils.load_template("error_page.html")) return response
def service(self, request): response = HttpResponse() response.set_header("Connection", "close") response.set_contents(utils.load_template("index.html", self.templates_dir)) now_playing = "" if "player" in self.context.keys() and self.context["player"] is not None: now_playing = self.context["player"].get_current_file() if now_playing is not None and not now_playing == "": splitted = now_playing.split("/") if splitted is not None and len(splitted) > 0: now_playing = splitted[-1] else: now_playing = "" response.set_attribute("now_playing", now_playing) return response
def generate_funcstub(funcname, funcsdict, typesdict): template = utils.load_template(FUNCSTUB_TEMPLATE) funcdict = funcsdict[funcname] args = funcdict['arguments'] returntype = funcdict['return_type'] # if no args remove args block in template template = utils.replace_template_block( template, 'args', repl=('' if len(args) == 0 else None), ) # if void, replace return block in template with just a return template = utils.replace_template_block( template, 'result', repl=('\nreturn;' if returntype == 'void' else None), ) template_formats = { 'funcname': funcname, 'returntype': returntype, 'declareArgs': '\n'.join([ utils.generate_vardecl(p['type'], p['name']) + ';' for p in args ]), 'readArgs': '\n'.join([ shared.generate_varreads(p['name'], p['type'], typesdict, True, 'ss') for p in args ]), 'callFunction': '{}{}({});'.format( '' if returntype == 'void' else (utils.generate_vardecl(returntype, 'res') + ' = '), funcname, ', '.join(p['name'] for p in args), ), 'resSizeAccumulate': shared.generate_varsize('res', returntype, typesdict, 'resSize'), 'sendRes': shared.generate_varwrites('res', returntype, typesdict, True), } return template.format(**template_formats)
def generate_funcproxy(funcname, funcsdict, typesdict): template = utils.load_template(FUNCPROXY_TEMPLATE) funcdict = funcsdict[funcname] args = funcdict['arguments'] returntype = funcdict['return_type'] # if no args, remove args block in template template = utils.replace_template_block( template, 'args', repl=('' if len(args) == 0 else None), ) # if void, replace result block in template with just a return void_return_str = '\n'.join([ 'debugStream << "Call to {funcname}() complete";', 'logDebug(debugStream, C150APPLICATION, true);', 'return;', ]) template = utils.replace_template_block( template, 'result', repl=(void_return_str if returntype == 'void' else None), ) template_formats = { 'funcname': funcname, 'returntype': returntype, 'funcheader': utils.generate_funcheader(funcname, funcdict), 'argsSizeAccumulate': ''.join([ shared.generate_varsize(p['name'], p['type'], typesdict, 'argsSize') for p in args ]), 'sendArgs': '\n'.join([ shared.generate_varwrites(p['name'], p['type'], typesdict, False) for p in args ]), 'declareResult': utils.generate_vardecl(returntype, 'res') + ';', 'readResult': shared.generate_varreads('res', returntype, typesdict, False, 'ss'), } return template.format(**template_formats)
def service(self, request): response = HttpResponse() response.set_header("Connection", "close") response.set_contents( utils.load_template("index.html", self.templates_dir)) now_playing = "" if "player" in self.context.keys( ) and self.context["player"] is not None: now_playing = self.context["player"].get_current_file() if now_playing is not None and not now_playing == "": splitted = now_playing.split("/") if splitted is not None and len(splitted) > 0: now_playing = splitted[-1] else: now_playing = "" response.set_attribute("now_playing", now_playing) return response
def add_categories_to_product(*args, **kwargs): cat_list = kwargs['query_string'].get('init_cat') product_name = kwargs['query_string'].get('prod_name') db = create_connection() cursor = db.cursor() try: cursor.execute(sql_assign_product_to_category(product_name, cat_list)) db.commit() except db.OperationalError: return load_template('admin_header') + "Product must have at least one category! " + load_template('footer') cursor.close() cursor = db.cursor() cursor.execute(sql_del_category_from_product(product_name, cat_list)) db.commit() cursor.close() db.close() return view_product()
def generate_dispatch(funcsdict, prefix): template = utils.load_template(DISPATCH_TEMPLATE) template = utils.replace_template_block( template, 'branches', repl=('' if len(funcsdict.keys()) == 0 else None), ) template_formats = { 'funcBranches': ' else '.join([ '\n'.join([ 'if (strcmp(funcname, "{0}") == 0) {{', ' writeInt(RPCSTUBSOCKET, existing_func);', ' _{0}();', '}}', ]).format(f) for f in funcsdict.keys() ]), } return template.format(**template_formats)
def edit_note(request, target_id): if request.startswith("POST"): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params = {} # Preencha o dicionário params com as informações do corpo da requisição # O dicionário conterá dois valores, o título e a descrição. # Posteriormente pode ser interessante criar uma função que recebe a # requisição e devolve os parâmetros para desacoplar esta lógica. # Dica: use o método split da string e a função unquote_plus for chave_valor in corpo.split('&'): split_chave_valor = chave_valor.split('=') split_novo1 = urllib.parse.unquote_plus(split_chave_valor[0]) split_novo2 = urllib.parse.unquote_plus(split_chave_valor[1]) params[split_novo1] = split_novo2 params['id'] = target_id edit_from_json(target_id, params, 'notes.json') return build_response(code=303, reason='See Other', headers='Location: /') if request.startswith("GET"): notes = load_data('notes.json') target = None for note in notes: if note['id'] == target_id: target = note break return build_response( load_template('edit.html').format(title=target['titulo'], details=target['detalhes'], id=target['id']))
def error_page(request): return build_response(load_template('error.html'))
def assert_template_loaded(self, filename, expected): m = mock_open(read_data=expected) with patch('utils.open', m): received = utils.load_template(filename) self.assertEqual(expected, received) self.assertEqual(Path(m.call_args[0][0]), Path('templates') / filename)
def __init__(self, *args, **kwargs): super(OneFileLayout, self).__init__(*args, **kwargs) self.outfileName = self.backendConfig.get("HEADER_OUTPUT") or None assert self.outfileName is not None, "HEADER_OUTPUT variable MUST be specified in the backend config. This is the file to the generated code for all nodes will be written to." self.templateName = self.backendConfig.get("HEADER_TEMPLATE") or DEFAULT_ONEFILE_TEMPLATE self.template = utils.load_template(self.templateName)
print("==> Fetching ArXiv ML RSS") page = requests.get(url).content.decode('utf-8') write_page(page) update_config('latest', date.today().strftime('%d%m%Y')) else: print("==> Loading saved ArXiv ML homepage") page = load_page() tree = ET.fromstring(page) # abstracts start from tree[2] count = 0 # start writing html page html_content = utils.load_template() table_highlight_rows = [] table_rows = [] for item in tree[2:]: print("###############################################") print("Paper no.", count+1) _, abs_link = item.attrib.popitem() # paper id paper_id = abs_link.split('/')[-1] print(paper_id) # paper title paper_title = item[0].text.split('(arXiv')[0][:-2]
def html2(username='', password=''): return load_template('hello.html').format(username=username, password=password)
def service(self, request): response = HttpResponse() response.set_header("Connection", "close") response.set_contents(utils.load_template("index.html", self.templates_dir)) response.set_attribute("title", "Home python server") return response
# Load all python files in the directory (and subdirectories) output = argv[2] if not os.path.isdir(output): os.mkdir(output) files = utils.get_all_files(argv[1], '.py') Tag.load_tags('tags.yaml', True) # Convert all python files into AST objects classes = [] functions = [] for file in files: _ast = utils.load_ast(file) classes.extend(utils.get_classes(_ast)) functions.extend(utils.get_functions(_ast)) # Create the readme, then create all subsequent data = get_data(classes, functions, output) readme_template = utils.load_template("../templates/readme.md", True) md = readme_template.render(data) with open(os.path.join(output, 'README.md'), 'w') as file: file.write(md) # Create file for each class class_template = utils.load_template("../templates/class.md", True) for class_data in data['classes']: md = class_template.render(class_data) file_path = os.path.join(output, class_data['name'] + '.md') with open(file_path, 'w') as file: file.write(md)
def index(request): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') try: corpo = partes[1] final = partes[-1] selecionar_str = final[-1] except: selecionar_str = "0" if selecionar_str == "1": id_corpo = corpo.split("&") id_init = id_corpo[0].split("=") id_corpo_str = id_init[1] id_corpo_int = int(id_corpo_str) note_template = load_template('components/update_note.html') note_template2 = load_template('components/note.html') dados = all_data("data/banco_notes") dados_mod = dados for index, item in enumerate(dados): if item.id == id_corpo_int: id_dados = item.id title_dados = item.title content_dados = item.content dados_mod.remove(item) notes_li = [ note_template.format(id=id_dados, title=title_dados, details=content_dados) ] notes_li2 = [ note_template2.format( title=dados.title, details=dados.content, id=dados.id, ) for dados in dados_mod ] notes_total = notes_li + notes_li2 notes = '\n'.join(notes_total) return build_response(load_template('index.html').format(notes=notes)) elif selecionar_str == "2": request = request.replace('\r', '') partes = request.split('\n\n') corpo = partes[1] id_corpo = corpo.split("&") id_init = id_corpo[0].split("=") id_corpo_str = id_init[1] delete_Entry(id_corpo_str, "data/banco_notes") note_template = load_template('components/note.html') notes_li = [ note_template.format( title=dados.title, details=dados.content, id=dados.id, ) for dados in all_data("data/banco_notes") ] notes = '\n'.join(notes_li) return build_response(code=303, reason='See Other', headers='Location: /') elif selecionar_str == "3": request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params_1 = {} for chave_valor in corpo.split('&'): half = chave_valor.split("=") chave = urllib.parse.unquote_plus(half[0], encoding='utf-8', errors='replace') valor = urllib.parse.unquote_plus(half[1], encoding='utf-8', errors='replace') params_1[chave] = valor params = dict(params_1) del params["selecionar"] update_Entry(params, "data/banco_notes") return build_response(code=303, reason='See Other', headers='Location: /') # A string de request sempre começa com o tipo da requisição (ex: GET, POST) else: if request.startswith('POST'): request = request.replace('\r', '') # Remove caracteres indesejados # Cabeçalho e corpo estão sempre separados por duas quebras de linha partes = request.split('\n\n') corpo = partes[1] params = {} for chave_valor in corpo.split('&'): half = chave_valor.split("=") chave = urllib.parse.unquote_plus(half[0], encoding='utf-8', errors='replace') valor = urllib.parse.unquote_plus(half[1], encoding='utf-8', errors='replace') params[chave] = valor add_Entry(params, "data/banco_notes") return build_response(code=303, reason='See Other', headers='Location: /') elif request.startswith('GET'): note_template = load_template('components/note.html') notes_li = [ note_template.format( title=dados.title, details=dados.content, id=dados.id, ) for dados in all_data("data/banco_notes") ] notes = '\n'.join(notes_li) return build_response( load_template('index.html').format(notes=notes))
def notfound(request, db): return load_template('404.html').encode()
def admin(*args, **kwargs): template = load_template('admin_header') + load_template('footer') return template
def add_category(*args, **kwargs): template = load_template('admin_header') + \ load_template('add_category') + \ load_template('footer') return template
def service(self, request): response = HttpResponse() response.set_contents( utils.load_template("media.html", self.templates_dir)) MEDIA_DIR = MUSIC_FILES_DIR if request.get_requested_page().startswith( "/music") else VIDEO_FILES_DIR media_type = "music" if MEDIA_DIR == MUSIC_FILES_DIR else "video" search_pattern = "^.*\.(mp3|wma|wav|)$" if media_type == "music" else "^.*\.(avi|flv|wmv|)$" file_names = {"dirs": [], "files": []} # getting requested sub-folder subdir = request.get_request_param("folder") if subdir is not None: subdir = urlparse.unquote(subdir, "utf-8") media_dir = os.path.join(MEDIA_DIR, subdir) else: media_dir = MEDIA_DIR subdir = "" # listing files, names of that will be sent to client files = [] try: files = os.listdir(media_dir) except FileNotFoundError as err: print("Directory wasn't found") for file in files: if re.match(search_pattern, file): file_names["files"].append([subdir, file]) elif os.path.isdir(os.path.join(media_dir, file)): file_names["dirs"].append([subdir, file]) files_list = "" if media_dir != MEDIA_DIR and media_dir[:-1] != MEDIA_DIR: parent_folder = os.path.dirname(media_dir) print("PARENT: " + parent_folder) if parent_folder != MEDIA_DIR: link = "{1}?folder={0}".format( parent_folder[len(MEDIA_DIR) + 1:], media_type) else: link = media_type files_list += "<div><a href=\"{0}\"><span class=\"folder\">{1}</span></a></div>\r\n"\ .format(link, "...") for folder in sorted(file_names["dirs"]): files_list += "<div><a href=\"{2}?folder={0}\"><span class=\"folder\">{1}</span></a>" \ "<span class=\"play-btn\" onclick=\"playFolder('{2}', '{0}')\">" \ "Play</span></div>\r\n"\ .format(os.path.join(folder[0], folder[1]), folder[1], media_type) for file in sorted(file_names["files"]): files_list += "<div onclick=\"playTrack('{2}', '{1}')\">{0}</div>\r\n".format( file[1], re.sub("'", "\\'", os.path.join(file[0], file[1])), media_type) response.set_attribute("files", files_list) now_playing = "" if "player" in self.context.keys( ) and self.context["player"] is not None: now_playing = self.context["player"].get_current_file() if now_playing is not None and not now_playing == "": splitted = now_playing.split("/") if splitted is not None and len(splitted) > 0: now_playing = splitted[-1] else: now_playing = "" response.set_attribute("now_playing", now_playing) title = "Video" if media_type == "video" else "Music" title += "" if subdir == "" else ": " + subdir response.set_attribute("title", title) return response