vitorsilverio / libraryapi Goto Github PK
View Code? Open in Web Editor NEWAn API to get MARC data from Pergamum.
Home Page: https://libraryapi.sites.ufsc.br/docs
License: GNU General Public License v3.0
An API to get MARC data from Pergamum.
Home Page: https://libraryapi.sites.ufsc.br/docs
License: GNU General Public License v3.0
Olá, ao fazer o merge das suas últimas alterações no gitlab da UFSC, a ferramenta parou de funcionar, veja:
https://codigos.ufsc.br/bu/libraryapi/-/commit/8054fbf4c39c3cd69679fdb1c0b15ed5cad5b311
Exemplo padrão que estava funcionando:
Obs.: Não tenho pressa :)
Utilizando o AsyncClient do zeep
, todo o código pode ser convertido para programação funcional com métodos assíncronos.
Além disso podemos remover a dependência do requests
e passar a usar a nova biblioteca mais usada para requisições http o httpx
.
É uma mudança simples porém precisamos nos certificar que nada quebrou.
Referencias
https://docs.python-zeep.org/en/master/client.html#the-asyncclient
https://docs.python-zeep.org/en/master/transport.html#async-http-authentication
I think it is a time to make a first major release 1.0. So we can remove the old syntax in a future version.
Antes das mudanças submetidas a pouco, fui tentar diagnosticar onde estava o problema nesta requisição: https://libraryapi-demo.herokuapp.com/pergamum/xml?url=https://pergamum.ufc.br/pergamum&id=2 . No terminal, dá a seguinte mensagem:
INFO: 127.0.0.1:42722 - "GET /pergamum/xml?url=https://pergamum.ufc.br/pergamum&id=2 HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File ".local/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File ".local/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File ".local/lib/python3.10/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File ".local/lib/python3.10/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File ".local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File ".local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File ".local/lib/python3.10/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File ".local/lib/python3.10/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File ".local/lib/python3.10/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File ".local/lib/python3.10/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File ".local/lib/python3.10/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File ".local/lib/python3.10/site-packages/fastapi/routing.py", line 226, in app
raw_response = await run_endpoint_function(
File ".local/lib/python3.10/site-packages/fastapi/routing.py", line 159, in run_endpoint_function
return await dependant.call(**values)
File "libraryapi/./app/main.py", line 27, in get_marc_xml
pergamumDownloader.get_marc_xml(url, id),
File "libraryapi/./libraryapi/pergamum.py", line 188, in get_marc_xml
self.build_record(url, id), namespace=True
File "libraryapi/./libraryapi/pergamum.py", line 179, in build_record
return Conversor.convert_dados_marc_to_record(dados_marc, id)
File "libraryapi/./libraryapi/pergamum.py", line 134, in convert_dados_marc_to_record
Conversor.build_field(paragrafo, indicador, descricao)
File "libraryapi/./libraryapi/pergamum.py", line 94, in build_field
[[subfield[0], subfield[2:]] for subfield in descricao[1:].split("$")]
File "libraryapi/./libraryapi/pergamum.py", line 94, in <listcomp>
[[subfield[0], subfield[2:]] for subfield in descricao[1:].split("$")]
IndexError: string index out of range
Fazendo uma consulta com o wget:
wget -O- --quiet --waitretry=3600 \
--header='Content-Type: text/xml; charset=utf-8' \
--post-data="<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:busca_marcwsdl\">
<soapenv:Header/>
<soapenv:Body>
<urn:busca_marc soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">
<codigo_acervo_temp xsi:type=\"xsd:int\">2</codigo_acervo_temp>
</urn:busca_marc>
</soapenv:Body>
</soapenv:Envelope>" "https://pergamum.ufc.br/pergamum/web_service/servidor_ws.php?wsdl" | sed -E 's/.*<return.*?>//g
s/<\/return>.*//g
s/<br\s?\/?\s?>//g
s/<(\/?Dados_marc|\/?paragrafo|\/?indicador|\/?descricao)>/<\1>/g
s/<\?xml version="1.0" encoding="UTF-8"\?>/<?xml version="1.0" encoding="UTF-8"?>/g
s/[\d1-\d31]|/ /g' | iconv -f ISO-8859-1 -t UTF-8
Retorna o seguinte:
<?xml version="1.0" encoding="UTF-8"?>
<Dados_marc>
<paragrafo>001</paragrafo>
<indicador> </indicador>
<descricao>2</descricao>
<paragrafo>003</paragrafo>
<indicador> </indicador>
<descricao>BR-FoUFC </descricao>
<paragrafo>005</paragrafo>
<indicador> </indicador>
<descricao>20191202212947.0 </descricao>
<paragrafo>008</paragrafo>
<indicador> </indicador>
<descricao>041209s1990 mgb# ### #000 0#por#d </descricao>
<paragrafo>020</paragrafo>
<indicador> </indicador>
<descricao>$c (Broch.) </descricao>
<paragrafo>040</paragrafo>
<indicador> </indicador>
<descricao>$a BR-FoUFC $c BR-FoUFC </descricao>
<paragrafo>082</paragrafo>
<indicador>0 4</indicador>
<descricao>$a 330.122 $2 20 </descricao>
<paragrafo>090</paragrafo>
<indicador> </indicador>
<descricao>$a 330.122 $b S663c $8 1 </descricao>
<paragrafo>100</paragrafo>
<indicador>1 </indicador>
<descricao>$a Sodré, Nelson Werneck, $d 1911-1999 </descricao>
<paragrafo>245</paragrafo>
<indicador>1 0</indicador>
<descricao>$a Capitalismo e revolucao burguesa no Brasil / $c Nelson Werneck Sodre. </descricao>
<paragrafo>260</paragrafo>
<indicador> </indicador>
<descricao>$a Belo Horizonte: $b Oficina de Livros, $c 1990. </descricao>
<paragrafo>300</paragrafo>
<indicador> </indicador>
<descricao>$a 203 p. </descricao>
<paragrafo>650</paragrafo>
<indicador>0 4</indicador>
<descricao>$a Capitalismo </descricao>
</Dados_marc>
Tem alguma ideia de onde está o problema?
https://pergamum.ufsc.br/pergamum está sendo resolvido como https://localhost:81/pergamum e os testes falham.
Provavelmente é alguma medida de proteção para que workflows não possam fazer requisições HTTP.
Ao tentar substituir a versão antiga (v1) pela versão nova (v2) aqui (opção "exportar"):
https://pergamum.ufsc.br/pergamum/biblioteca/index.php?word=os%20miser%C3%A1veis
Isto é, substituir o URL do tipo
https://libraryapi.sites.ufsc.br/pergamum/mrc?url=https://pergamum.ufsc.br/pergamum&id=226347
pelo
https://libraryapi.sites.ufsc.br/api/v2/pergamum/226347?url=https://pergamum.ufsc.br/pergamum/web_service/servidor_ws.php&media_type=application/marc
por alguma razão que desconheço, a opção application/marc
faz a página congelar. Isso não acontece com application/xml
ou text/plain
, por exemplo.
Se quiser testar, use o console do navegador:
const pmu_linha_top = document.querySelectorAll(".pmu_linha_top");
for (let elem of pmu_linha_top) {
let codAcervo = elem.parentElement.firstElementChild.lastChild.textContent;
let libraryApiParams = "?url=https://pergamum.ufsc.br/pergamum/web_service/servidor_ws.php&media_type=application/marc"
let exportUrl = "<a href='https://libraryapi.sites.ufsc.br/api/v2/pergamum/" + codAcervo + libraryApiParams + "' class='link_azul_claro' target='_blank' title='Salvar MARC ISO 2709'>(exportar)</a>";
for (let aElem of elem.children) {
if (aElem.matches('a[href*="marc"]')) {
aElem.insertAdjacentHTML("afterend", exportUrl);
}
}
}
E é justamente o formato application/marc
que precisa funcionar. Não entendi o que pode estar dando errado, talvez seja necessário mudar o formato padrão (sem especificar o param media_type
) para o marc_provider
, em vez do json_provider
aqui:
https://github.com/vitorsilverio/libraryapi/blob/main/app/main.py#L67
O que acha?
Estava tentando fazer um docker-compose.yml como ensinado naquele vídeo que me enviou, mas não consegui.
version: '3.3'
services:
app:
build: .
container_name: libraryapi
command: uvicorn app.main:app --port 80 --reload
ports:
- '80:80'
image: libraryapi:latest
volumes:
- .:/app
Quando faço o docker-compose up --build
dá:
Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "uvicorn": executable file not found in $PATH: unknown
A ideia é ter apenas um endpoint responsável pela ação comum evitando repetição de código.
O tipo de resposta deve ser pedido por um parametro GET ou pelo proprio Http Header Accept dando prioridade para o get param.
Além disso utilizando design pattern Strategy será possível implementar novos formato que forem necessários
curl "http://localhost/api/v2/pergamum/{id}" -H "Accept: application/marc" -H "Server: https://pergamum.ufsc.br/pergamum"
#permitindo também via get params
curl "http://localhost/api/v2/pergamum/{id}?server=https://pergamum.ufsc.br/pergamum&accept=application/xml"
A ideia é manter as urls anteriores por um tempo mas descontinuar para esse novo modelo
O que acha @jaideraf ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.