zliang commited on
Commit
588e8ae
1 Parent(s): 58ce433

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +22 -18
main.py CHANGED
@@ -32,28 +32,32 @@ def read_root():
32
  return HTMLResponse(content=html_content)
33
 
34
  @app.get("/title2ref/")
35
- async def title2doi(title:str):
36
  cr = Crossref()
37
 
38
- result = cr.works(query = title)
39
- for i, item in enumerate(result['message']['items']):
40
- if item['title'][0] == title:
41
- doi = result['message']['items'][i]['DOI']
42
- break
43
 
44
- url = BASE_URL + doi
45
- req = urllib.request.Request(url)
46
- req.add_header('Accept', 'application/x-bibtex')
 
 
 
 
 
47
 
48
- try:
49
- with urllib.request.urlopen(req) as f:
50
- bibtex = f.read().decode()
51
- return {"bibtex": bibtex}
52
- except HTTPError as e:
53
- if e.code == 404:
54
- raise HTTPException(status_code=404, detail="DOI not found")
55
- else:
56
- raise HTTPException(status_code=503, detail="Service unavailable")
 
 
 
57
 
58
  @app.get("/doi2ref/")
59
  async def doi2ref(doi: str):
 
32
  return HTMLResponse(content=html_content)
33
 
34
  @app.get("/title2ref/")
35
+ async def title2doi(title: str):
36
  cr = Crossref()
37
 
38
+ result = cr.works(query=title)
 
 
 
 
39
 
40
+ # Check if the result has items and the title matches
41
+ if result['message']['items']:
42
+ for item in result['message']['items']:
43
+ if 'title' in item and item['title'][0] == title:
44
+ doi = item['DOI']
45
+ url = BASE_URL + doi
46
+ req = urllib.request.Request(url)
47
+ req.add_header('Accept', 'application/x-bibtex')
48
 
49
+ try:
50
+ with urllib.request.urlopen(req) as f:
51
+ bibtex = f.read().decode()
52
+ return {"bibtex": bibtex}
53
+ except HTTPError as e:
54
+ if e.code == 404:
55
+ raise HTTPException(status_code=404, detail="DOI not found")
56
+ else:
57
+ raise HTTPException(status_code=503, detail="Service unavailable")
58
+
59
+ # If no matching title found
60
+ raise HTTPException(status_code=404, detail="Title not found, please enter DOI")
61
 
62
  @app.get("/doi2ref/")
63
  async def doi2ref(doi: str):