Giter Club home page Giter Club logo

libraryapi's People

Contributors

arthurd2 avatar dependabot[bot] avatar jaideraf avatar snyk-bot avatar vitorsilverio avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

jaideraf

libraryapi's Issues

Atualizar o client do zeep para AsyncClient

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.

Passos

  • Remover requests das dependencias
  • Importar o AsyncClient do httpx em vez do Session do requests
  • Importar o AsyncTransport em vez do Transport do zeep
  • Importar o AsyncClient do zeep em vez do Client
  • Criar uma instancia do AsyncClient do httpx e atualizar o header
  • Criar uma instancia do AsyncTransport e configurar o cliente
  • Criar uma instancia do AsyncClient do zeep e passar o transport como parametro
  • colocar async em todos os metodos que podem ser assincronos
  • colocar await nas respostas do zeep

Referencias
https://docs.python-zeep.org/en/master/client.html#the-asyncclient
https://docs.python-zeep.org/en/master/transport.html#async-http-authentication

Make a release

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.

Internal Server Error

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/&lt;br\s?\/?\s?&gt;//g
              s/&lt;(\/?Dados_marc|\/?paragrafo|\/?indicador|\/?descricao)&gt;/<\1>/g
              s/&lt;\?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;\?&gt;/<?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?

Opção application/marc quebra a página html do catálogo

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.
marc-congela-tela

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?

Aprendendo a fazer um docker-compose.yml

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

Usar o Design Pattern Strategy ara solucionar o problema dos Endpoints

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 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.