1+ from os .path import exists
2+
13from flask import request
24from flask_restx import Namespace , Resource , fields
35from markupsafe import escape
@@ -113,7 +115,6 @@ class GaiaPublicationFigures(Resource):
113115 @gaia .expect (publication_request_fields )
114116 def post (self ):
115117 json_data = request .get_json ()
116- data = {}
117118
118119 # Validate json
119120 try :
@@ -123,7 +124,7 @@ def post(self):
123124
124125 pubmeds = json_data ["pubmeds" ]
125126
126- # Check if pubmed ids are valide
127+ # Check if pubmed ids are valid
127128 for pubmed in pubmeds :
128129 if not BARUtils .is_integer (pubmed ):
129130 return BARUtils .error_exit ("Invalid Pubmed ID" ), 400
@@ -137,23 +138,42 @@ def post(self):
137138 .select_from (Figures )
138139 .join (PubIds , PubIds .publication_figures_id == Figures .publication_figures_id )
139140 .filter (PubIds .pubmed .in_ (pubmeds ))
141+ .order_by (PubIds .pubmed .desc ())
140142 )
141143
142144 rows = db .session .execute (query ).fetchall ()
143145
144- # Just output the rows for now, we will format later
146+ current_pubmed = ""
147+ record = {}
148+
145149 if rows and len (rows ) > 0 :
146150 for row in rows :
147- record = {
148- "img_name" : row .img_name ,
149- "caption" : row .caption ,
150- "img_url" : row .img_url ,
151- "pubmed" : row .pubmed ,
152- "pmc" : row .pmc ,
153- }
154-
155- # Add the record to data
156- data .append (record )
151+
152+ # Check if record has an id. If it doesn't, this is first row.
153+ if "id" in record :
154+ # Check if this is a new pubmed id
155+ if record ["id" ]["pubmed" ] != row .pubmed :
156+ # new record. Add old now to data and create a new record
157+ data .append (record )
158+ record = {}
159+
160+ # Check if figures exists, if not add it.
161+ if record .get ("figures" ) is None :
162+ # Create a new figures record
163+ record ["figures" ] = []
164+
165+ # Now append figure to the record
166+ figure = {"img_name" : row .img_name , "caption" : row .caption , "img_url" : row .img_url }
167+ record ["figures" ].append (figure )
168+
169+ # Now add the id. If it exists don't add
170+ if record .get ("id" ) is None :
171+ record ["id" ] = {}
172+ record ["id" ]["pubmed" ] = row .pubmed
173+ record ["id" ]["pmc" ] = row .pmc
174+
175+ # The last record
176+ data .append (record )
157177
158178 # Return final data
159179 return BARUtils .success_exit (data )
0 commit comments