Home > other >  The API returns <Response 200> but I don't see the result
The API returns <Response 200> but I don't see the result

Time:11-13

To explain my problem, I'm a beginner in Python and I've got to do a loop in Python to make an automatic map production in Qgis. There are 2 facts. The first is that I'm using the French Government's API called "Addresses" that return addresses (and many data linked to this address) from geographic coordinates. When I run my code in the Qgis python console, the response is 200 but I don't see anything appearing. This is a real problem for me because I want to import those pieces of information into my Layout and I don't know how to do this too (this is the second fact).

Here I show you the code I have with the API :

for feat in mylayer.getFeatures():
Shops_name = feat['nom_sho']
x = feat['x'] #x and Y stands for longitude and latitude
y = feat['y']
x = str(x)
y = str(y)
date = datetime.date.today()
today = str(date)
expr = u"nom_sho = '{}'".format(Shops_name)
myselect = mylayer.getFeatures( QgsFeatureRequest().setFilterExpression ( expr ))
iface.mapCanvas().zoomToSelected(mylayer)
iface.mapCanvas().zoomScale(1625)
print(f"Voici {Shops_name}" )

mylayer.selectByIds( [ f.id() for f in myselect ] )

project = QgsProject.instance()
manager = project.layoutManager()
layoutName = str(Shops_name)

#layout

layouts_list = manager.printLayouts()
for layout in layouts_list:
    if layout.name() == layoutName:
        manager.removeLayout(layout)

layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.setName(layoutName)
manager.addLayout(layout)

#symbology

symbol_shop = QgsMarkerSymbol.createSimple({'name': 'Triangle', 'color': '#0088CC', 'outline_color': 'black', 'size': '4'})
symbol_shop_selected = QgsMarkerSymbol.createSimple({'name': 'Triangle', 'color': 'blue', 'outline_color': 'black', 'size': '7'})

color_shop = QgsRendererCategory(None,symbol_shop,"Other shops",True)
color_shop_selected = QgsRendererCategory(layoutName,symbol_shop_selected,layoutName,True)

renderer = QgsCategorizedSymbolRenderer("nom_sho", [color_shop,color_shop_selected])

mylayer.setRenderer(renderer)
mylayer.triggerRepaint()

# empty map 
map = QgsLayoutItemMap(layout)
map.setRect(20, 20, 20, 20)
# layout2
rectangle = QgsRectangle(1355502, -46398, 1734534, 137094)
map.setExtent(rectangle)
layout.addLayoutItem(map)

# Canva update
canvas = iface.mapCanvas()
map.setExtent(canvas.extent())
layout.addLayoutItem(map)
# Resize map
map.attemptMove(QgsLayoutPoint(5, 27, QgsUnitTypes.LayoutMillimeters))
map.attemptResize(QgsLayoutSize(220, 178, QgsUnitTypes.LayoutMillimeters))

# Legende
tree_layers = project.layerTreeRoot().children()
checked_layers = [layer.name() for layer in tree_layers if layer.isVisible()]
layers_to_remove = [layer for layer in project.mapLayers().values() if layer.name() not in checked_layers]
legend = QgsLayoutItemLegend(layout)
legend.setTitle(html.unescape("L&eacute;gende"))
legend.setStyleFont(QgsLegendStyle.Title, myBoldFont)
layout.addLayoutItem(legend)
legend.attemptMove(QgsLayoutPoint(230, 24, QgsUnitTypes.LayoutMillimeters))

legend.setAutoUpdateModel(False) 
m = legend.model()
g = m.rootGroup()
for l in layers_to_remove:
    g.removeLayer(l)

g.removeLayer(osm)
legend.adjustBoxSize()

#api

r = requests.get("https://api-adresse.data.gouv.fr/reverse/?lon=" x "&lat=" y "")
r.json()
print(r)

# Title
title = QgsLayoutItemLabel(layout)
title.setText(layoutName)
title.setFont(myTitleBoldFont)
title.adjustSizeToText()
layout.addLayoutItem(title)
title.attemptMove(QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters))

# Subtitle
subtitle = QgsLayoutItemLabel(layout)
subtitle.setFont(QFont("Verdana", 18))
subtitle.adjustSizeToText()
layout.addLayoutItem(subtitle)
subtitle.attemptMove(QgsLayoutPoint(5, 18, QgsUnitTypes.LayoutMillimeters))

# Scale
scalebar = QgsLayoutItemScaleBar(layout)
scalebar.setStyle('Single Box')
scalebar.setUnits(QgsUnitTypes.DistanceMeters)
scalebar.setNumberOfSegments(2)
scalebar.setNumberOfSegmentsLeft(0)
scalebar.setUnitsPerSegment(25)
scalebar.setLinkedMap(map)
scalebar.setUnitLabel('km')
scalebar.setFont(QFont('Verdana', 20))
scalebar.update()
layout.addLayoutItem(scalebar)
scalebar.attemptMove(QgsLayoutPoint(10, 185, QgsUnitTypes.LayoutMillimeters))

Thank you for your help.

CodePudding user response:

Use r.json() to print in json format. can use r.text r.content as well

CodePudding user response:

Here is a good source of information about the get request response. https://www.w3schools.com/python/ref_requests_response.asp

What you want to do is get the body of the response. You will probably want to use r.json().

  • Related