Debian Codegraph @

examples/error_handling.py

raw
1 from dotenv import load_dotenv, find_dotenv
2 from oauthcli import OpenStreetMapDevAuth
3 from oauthlib.oauth2.rfc6749.errors import OAuth2Error
4 import logging
5 import os
6 import osmapi
7 import requests
8 import subprocess
9 import sys
10 import urllib3
11
12 load_dotenv(find_dotenv())
13
14 # logging setup
15 log = logging.getLogger(__name__)
16 loglevel = logging.DEBUG
17 logging.basicConfig(
18 format="%(asctime)s %(name)s %(levelname)-8s %(message)s",
19 level=loglevel,
20 datefmt="%Y-%m-%d %H:%M:%S",
21 )
22 logging.captureWarnings(True)
23
24 # shut up DEBUG messages of specific loggers
25 logging.getLogger(osmapi.dom.__name__).setLevel(logging.INFO)
26 logging.getLogger(urllib3.__name__).setLevel(logging.INFO)
27
28
29 def clear_screen():
30 # check and make call for specific operating system
31 _ = subprocess.call("clear" if os.name == "posix" else "cls")
32
33
34 # The error handling with osmapi is very easy, simply catch the
35 # exception for the specific case you want to handle.
36 # - All osmapi excepctions are child classes of osmapi.OsmApiError
37 # - Errors that result from the communication with the OSM server osmapi.ApiError
38 # - There are a number of subclasses to differantiate the different errors
39 # - catch more specific errors first, then use more general error classes
40
41 # Upload data to OSM without a changeset
42 log.debug("Try to write data to OSM without a changeset")
43 api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org")
44 try:
45 node1 = api.node_create({"lon": 1, "lat": 1, "tag": {}})
46 except osmapi.NoChangesetOpenError as e:
47 log.exception(e)
48 log.debug("There is no open changeset")
49 input("Press Enter to continue...")
50 clear_screen()
51
52
53 # wrong server: ConnectionError
54 log.debug("Connect to wrong server...")
55 api = osmapi.OsmApi(api="https://invalid.server.name")
56 try:
57 api.changeset_get(123)
58 except osmapi.ConnectionApiError as e:
59 log.exception(e)
60 log.debug("Error connecting to server")
61 input("Press Enter to continue...")
62 clear_screen()
63
64
65 # changeset not found: ElementNotFoundApiError
66 log.debug("Request non-existent changeset id...")
67 api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org")
68 try:
69 api.changeset_get(111111111111)
70 except osmapi.ElementNotFoundApiError as e:
71 log.exception(e)
72 log.debug("Changeset not found")
73 input("Press Enter to continue...")
74 clear_screen()
75
76
77 # unauthorized request
78 log.debug("Try to add data with wrong authorization")
79 try:
80 s = requests.Session()
81 s.auth = ("user", "pass")
82 api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org", session=s)
83 with api.changeset({"comment": "My first test"}) as changeset_id:
84 node1 = api.node_create({"lon": 1, "lat": 1, "tag": {}})
85 except osmapi.UnauthorizedApiError as e:
86 log.exception(e)
87 log.debug("Unauthorized to make this request")
88 input("Press Enter to continue...")
89 clear_screen()
90
91 # request without auhorization
92 log.debug("Try to add data without authorization")
93 try:
94 api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org")
95 with api.changeset({"comment": "My first test"}) as changeset_id:
96 node1 = api.node_create({"lon": 1, "lat": 1, "tag": {}})
97 except osmapi.AuthenticationMissingError as e:
98 log.exception(e)
99 log.debug("No authenticated session provided for this request")
100 input("Press Enter to continue...")
101 clear_screen()
102
103
104 # a more or less complete "real-life" example
105 client_id = os.getenv("OSM_OAUTH_CLIENT_ID")
106 client_secret = os.getenv("OSM_OAUTH_CLIENT_SECRET")
107
108 try:
109 auth = OpenStreetMapDevAuth(
110 client_id, client_secret, ["write_api", "write_notes"]
111 ).auth_code()
112 except OAuth2Error as e:
113 log.exception(e)
114 log.debug("An OAuth2 error occured")
115 sys.exit(1)
116
117 try:
118 api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org", session=auth.session)
119 with api.changeset({"comment": "My first test"}) as changeset_id:
120 log.debug(f"Part of Changeset {changeset_id}")
121 node1 = api.node_create({"lon": 1, "lat": 1, "tag": {}})
122 log.debug(node1)
123
124 # get all the info from the closed changeset
125 changeset = api.changeset_get(changeset_id)
126 log.debug(changeset)
127 exit_code = 0
128 except osmapi.ConnectionApiError as e:
129 log.debug(f"Connection error: {str(e)}")
130 exit_code = 1
131 # display error for user, try again?
132 except osmapi.ElementNotFoundApiError as e:
133 log.debug(f"Changeset not found: {str(e)}")
134 exit_code = 1
135 except osmapi.ApiError as e:
136 log.debug(f"Error on the API side: {str(e)}")
137 exit_code = 1
138 except osmapi.OsmApiError as e:
139 log.debug(f"Some other error: {str(e)}")
140 exit_code = 1
141 finally:
142 log.debug(f"Exit code: {exit_code}")
143 sys.exit(exit_code)