How to use xml_response method in localstack

Best Python code snippet using localstack_python

main.py

Source:main.py Github

copy

Full Screen

...126 return BeautifulSoup(requests.get(html_link).text,'html.parser')127 except Exception as ex:128 exception_list.append(ex)129 return ""130def get_xml_response(xml_link):131 try:132 return BeautifulSoup(requests.get(xml_link).text,'xml')133 except Exception as ex:134 exception_list.append(ex)135 return ""136xml_link = "https://www.sec.gov/Archives/edgar/data/36405/000175272420251139/primary_doc.xml"137html_link = "https://www.sec.gov/Archives/edgar/data/911507/000175272420007705/0001752724-20-007705-index.htm"138def create_csv(xml_link,html_link):139 try:140 #handle logic here like get xml and html response at first and then do processing :)141 #this will save amount of request sent to server142 #then read the url list and get all necessary links from there143 #build the corresponding csv as mentioned144 #then run these two functions one by one...

Full Screen

Full Screen

app.py

Source:app.py Github

copy

Full Screen

1from flask import Flask, request2import flask3import xmltodict4from ORM.models import DB_Admin, Juego5from flask_cors import CORS6from sqlite3 import connect7#Temporal8from random import randint9app = Flask(__name__)10CORS(app)11@app.route('/')12def main():13 gamenum = randint(1,10000)14 devnum = randint(1,10000)15 disnum = randint(1,10000)16 juego = Juego((None, f'Juego {gamenum}', f'dev {devnum}', f'dis {disnum}', 'DD MMM AAAA', 'qdboauysdbuwdq', randint(1000,10000)))17 juego.save()18 juegos = Juego.get_all()19 return str([str(juego) for juego in juegos])20@app.route('/clear')21def clear():22 Juego.clear_all()23 return 'done'24@app.route('/juegos',methods = ['POST']) #Sirve para mostrar todo el catalogo25def mostrar_catalogo():26 juegos = Juego.get_all()27 xml_response = '<?xml version="1.0" encoding="UTF-8"?><juegos>'28 for juego in juegos:29 xml_response += juego.to_xml()30 xml_response += '</juegos>'31 resp = flask.Response(xml_response, content_type='application/xml')32 resp.headers['Access-Control-Allow-Origin'] = '*'33 return resp34 35@app.route('/juegos/filtros', methods = ['POST'])# Sirve para aplicar los filtros de la primera pagina36def juegos_filtros():37 request.get_data()38 print(request.data)39 xml_info = xmltodict.parse(request.data)40 #print(xml_info)41 query =''42 if xml_info["juego"]["titulo"] != None:43 query += f' WHERE titulo LIKE "%{xml_info["juego"]["titulo"]}%"'44 if xml_info["juego"]["desarrollador"] != None:45 if query != '':46 query += " AND"47 else:48 query += ' WHERE'49 query += f' desarrollador LIKE "%{xml_info["juego"]["desarrollador"]}%"'50 if xml_info["juego"]["distribuidor"] != None:51 if query != '':52 query += " AND"53 else:54 query += " WHERE"55 query += f' distribuidor LIKE "%{xml_info["juego"]["distribuidor"]}%"'56 57 con = connect(DB_Admin.DB_NAME)58 cur = con.cursor()59 cur.execute(f'SELECT * FROM juegos{query}')60 dats = cur.fetchall()61 juegos = [Juego(dat) for dat in dats]62 con.close()63 #print(dats)64 xml_response = '<?xml version="1.0" encoding="UTF-8"?><juegos>'65 for juego in juegos:66 xml_response += juego.to_xml()67 xml_response += '</juegos>'68 resp = flask.Response(xml_response, content_type='application/xml')69 resp.headers['Access-Control-Allow-Origin'] = '*'70 return resp71@app.route('/juegos/compra',methods = ['POST']) # Regresa la información de un juego 72def info_juego():73 xml_info = xmltodict.parse(request.data)74 if xml_info["juego"]["id"] != None:75 con = connect(DB_Admin.DB_NAME)76 cur = con.cursor()77 cur.execute(f'SELECT * FROM juegos WHERE id = "{xml_info["juego"]["id"]}"')78 dats = cur.fetchall()79 juegos = [Juego(dat) for dat in dats]80 con.close()81 #print(dats)82 xml_response = '<?xml version="1.0" encoding="UTF-8"?><juegosFiltros>'83 for juego in juegos:84 xml_response += juego.to_xml()85 xml_response += '</juegosFiltros>'86 resp = flask.Response(xml_response, content_type='application/xml')87 resp.headers['Access-Control-Allow-Origin'] = '*'88 return resp89 else:90 resp = make_response(dumps({'response' : 'Error'},404))91 resp.headers.extend(headers or {})92 return resp93 94@app.route('/juego/compras/transaccion',methods = ['POST'])95def transaccion():96 xml_info = xmltodict.parse(request.data)97 if xml_info["compra"]["usuario"]["id"] != None:98 if ["compra"]["juego"]["id"] != None:99 con = connect(DB_Admin.DB_NAME)100 cur = con.cursor()101 cur.execute(f'SELECT credito FROM usuarios WHERE id = {id}')102 creditoUsuario = cur.fetchall()103 cur.execute(f'SELECT precio FROM juego WHERE id = {idjuego}')104 precioJuego = cur.fetchall()105 nuevoCredito = creditoUsuario - precioJuego106 if nuevoCredito >= 0:107 cur.execute(f'UPDATE usuarios SET credito = {nuevoCredito} WHERE id = {id}')108 con.close()109 resp = make_response(dumps({},200))110 return resp111 else:112 con.close()113 xml_response = '<?xml version="1.0" encoding="UTF-8"?><errorCredito>'114 xml_response = f'<error>El usuario no tiene el suficiente credito</error>'115 xml_response += '</errorCredito>'116 resp = flask.Response(xml_response, content_type='application/xml')117 resp.headers['Access-Control-Allow-Origin'] = '*'118 return resp119 else:120 con.close()121 xml_response = '<?xml version="1.0" encoding="UTF-8"?><errorCredito>'122 xml_response = f'<error>No se encuentra el juego deseado</error>'123 xml_response += '</errorCredito>'124 resp = flask.Response(xml_response, content_type='application/xml')125 resp.headers['Access-Control-Allow-Origin'] = '*'126 return resp127 else:128 con.close()129 xml_response = '<?xml version="1.0" encoding="UTF-8"?><errorCredito>'130 xml_response = f'<error>No se encuentra el usuario</error>'131 xml_response += '</errorCredito>'132 resp = flask.Response(xml_response, content_type='application/xml')133 resp.headers['Access-Control-Allow-Origin'] = '*'134 return resp135 136@app.route('/juegos/registros', methods = ['POST'])137def nuevo_juego():138 xml_info = xmltodict.parse(request.data)139 juego = Juego((None, xml_info["juego"]["titulo"], xml_info["juego"]["desarrollador"], xml_info["juego"]["distribuidor"], xml_info["juego"]["fechalanzamiento"], xml_info["juego"]["descripcion"], xml_info["juego"]["precio"]["#text"]))140 juego.save()141 juegos = Juego.get_all()142 return str([str(juego) for juego in juegos])143 return 'done'144if __name__ == '__main__':145 DB_Admin.start_db()...

Full Screen

Full Screen

google_weather_api.py

Source:google_weather_api.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import re3import urllib24import unicodedata5from urllib import urlencode6from traceback import print_exc7from xml.dom.minidom import parseString8from locale import getdefaultlocale9DEFAULT_HL = str( getdefaultlocale() )[ 2:4 ].lower() or "en"10GOOGLE_WEATHER_URL = 'http://www.google.com/ig/api?'11GOOGLE_COUNTRIES_URL = 'http://www.google.com/ig/countries?'12GOOGLE_CITIES_URL = 'http://www.google.com/ig/cities?'13def _unicode( text, encoding='utf-8' ):14 try: text = unicode( text, encoding )15 except: pass16 return text17def normalize_string( text ):18 try: text = unicodedata.normalize( 'NFKD', _unicode( text ) ).encode( 'ascii', 'ignore' )19 except: pass20 return text21def getData( elem, tag, clean=False ):22 try: data = elem.getElementsByTagName( tag )[ 0 ].getAttribute( "data" )23 except: data = ""24 if clean:25 data = data.split( ": ", 1 )[ -1 ]26 return data27def parse_response( xml_response ):28 dom = parseString( xml_response )29 if __name__ == "__main__":30 print dom.toprettyxml()31 return dom32def get_google_response( url ):33 sock = urllib2.urlopen( url )34 #Content-Type: text/html; charset=ISO-8859-135 contentType = sock.info().get( 'content-type' ) or ''36 encoding = ''.join( re.findall( 'charset\=(.*)', contentType ) )37 if not encoding:38 encoding = 'utf-8'39 xml_response = sock.read()40 if encoding.lower() != 'utf-8':41 try: xml_response = xml_response.decode( encoding ).encode( 'utf-8' )42 except: print_exc()43 sock.close()44 return xml_response45def get_weather( weather, hl=DEFAULT_HL ):46 """ Fetches weather report from Google47 Parameters48 weather: 49 - by zip code (10001)50 - by city name, state (woodland,PA) 51 - by city name, country (london, england);52 - by latitude+longitude (,,,30670000,104019996)53 hl: the language parameter (language code). Default value is empty string, in this case Google will use English.54 """55 #use locals() is { "hl": hl, "weather": weather }56 data = urlencode( locals() )57 url = GOOGLE_WEATHER_URL + data58 xml_response = get_google_response( url )59 return parse_response( xml_response )60def get_countries( hl=DEFAULT_HL, output='xml' ):61 """ Get list of countries in specified language from Google62 Parameters63 hl: the language parameter (language code). Default value is empty string, in this case Google will use English.64 """65 data = urlencode( locals() )66 url = GOOGLE_COUNTRIES_URL + data67 xml_response = get_google_response( url )68 dom = parse_response( xml_response )69 countries = []70 for country in dom.getElementsByTagName( 'country' ):71 country = ( getData( country, "name" ), getData( country, "iso_code" ) )72 countries.append( country )73 dom.unlink()74 return sorted( countries, key=lambda c: normalize_string( c[ 0 ] ).lower() )75def get_cities( country, hl=DEFAULT_HL, output='xml' ):76 """ Get list of cities of necessary country in specified language from Google77 Parameters78 country_code: code of the necessary country. For example 'de' or 'fr'.79 hl: the language parameter (language code). Default value is empty string, in this case Google will use English.80 """81 country = country.lower()82 data = urlencode( locals() )83 url = GOOGLE_CITIES_URL + data84 xml_response = get_google_response( url )85 dom = parse_response( xml_response )86 cities = []87 for city in dom.getElementsByTagName( 'city' ):88 coord = ",,,%s,%s" % ( getData( city, "latitude_e6" ), getData( city, "longitude_e6" ) )89 city = getData( city, "name" )90 cities.append( ( city, coord ) )91 dom.unlink()92 return sorted( cities, key=lambda c: normalize_string( c[ 0 ] ).lower() )93if __name__ == "__main__":94 #print get_weather( 'Quebec,,,52939916,-73549136' )#'g1j3p8' ) 95 #print get_countries()96 #print get_cities( "CA" )97 url = "http://www.sunrisesunset.com/mobile/day.asp?latitude=52.939916&latitude_n_s=N&longitude=73.549136&longitude_e_w=W&timezone=-6&dayOfMonth=11&month=11&year=2011"...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful