Hallo Community,
Ich habe hier ein Open Source Projekt basierend auf Python. Leider blicke ich bei Python nur äußerst spärlich durch. Dennoch könnte ich den Code sehr gut in einem Projekt von mir gebrauchen.
Konkret geht es darum, sich auf eine Mobile Api zu verbinden und daten (über cookies) auszulesen.
Da ich noch anfänger bin bräuchte ich den code, um mich daran zu orientieren und erstmal richtig zu verstehen was ich da genau mache.
hier der denke ich relevanteste teil
Der komplette Code (falls relevant) befindet sich im Anhang
Vielen dank schon mal
Anhang anzeigen edapi.txt
(ist eine.py datei, aber man kann keine .py hochladen, daher.txt)
Ich habe hier ein Open Source Projekt basierend auf Python. Leider blicke ich bei Python nur äußerst spärlich durch. Dennoch könnte ich den Code sehr gut in einem Projekt von mir gebrauchen.
Konkret geht es darum, sich auf eine Mobile Api zu verbinden und daten (über cookies) auszulesen.
Da ich noch anfänger bin bräuchte ich den code, um mich daran zu orientieren und erstmal richtig zu verstehen was ich da genau mache.
hier der denke ich relevanteste teil
Code:
class EDAPI:
'''
A class that handles the Frontier ED API.
'''
_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411' # NOQA
_baseurl = 'https://companion.orerve.net/'
_basename = 'edapi'
_cookiefile = _basename + '.cookies'
_envfile = _basename + '.vars'
def __init__(
self,
basename='edapi',
debug=False,
cookiefile=None,
json_file=None
):
'''
Initialize
'''
# Build common file names from basename.
self._basename = basename
if cookiefile:
self._cookiefile = cookiefile
else:
self._cookiefile = self._basename + '.cookies'
self._envfile = self._basename + '.vars'
self.debug = debug
# If json_file was given, just load that instead.
if json_file:
with open(json_file) as file:
self.profile = json.load(file)
return
# if self.debug:
# import http.client
# http.client.HTTPConnection.debuglevel = 3
# Setup the HTTP session.
self.opener = requests.Session()
self.opener.headers = {
'User-Agent': self._agent
}
# Read/create the cookie jar.
if os.path.exists(self._cookiefile):
try:
with open(self._cookiefile, 'rb') as h:
self.opener.cookies = cookiejar_from_dict(pickle.load(h))
except:
print('Unable to read cookie file.')
else:
with open(self._cookiefile, 'wb') as h:
pickle.dump(dict_from_cookiejar(self.opener.cookies), h)
# Grab the commander profile
response = self._getURI('profile')
try:
self.profile = response.json()
except:
sys.exit('Unable to parse JSON response for /profile!\
Try with --debug and report this.')
def _getBasicURI(self, uri, values=None):
'''
Perform a GET/POST to a URI
'''
# POST if data is present, otherwise GET.
if values is None:
if self.debug:
print('GET on: ', self._baseurl+uri)
print(dict_from_cookiejar(self.opener.cookies))
response = self.opener.get(self._baseurl+uri)
else:
if self.debug:
print('POST on: ', self._baseurl+uri)
print(dict_from_cookiejar(self.opener.cookies))
response = self.opener.post(self._baseurl+uri, data=values)
if self.debug:
print('Final URL:', response.url)
print(dict_from_cookiejar(self.opener.cookies))
# Save the cookies.
with open(self._cookiefile, 'wb') as h:
pickle.dump(dict_from_cookiejar(self.opener.cookies), h)
# Return the response object.
return response
def _getURI(self, uri, values=None):
'''
Perform a GET/POST and try to login if needed.
'''
# Try the URI. If our credentials are no good, try to
# login then ask again.
response = self._getBasicURI(uri, values=values)
if str(response.url).endswith('user/login'):
self._doLogin()
response = self._getBasicURI(uri, values=values)
if str(response.url).endswith('user/login'):
sys.exit(textwrap.fill(textwrap.dedent("""\
Something went terribly wrong. The login credentials
appear correct, but we are being denied access. Sometimes the
API is slow to update, so if you are authenticating for the
first time, wait a minute or so and try again. If this
persists try using --debug and report this.
""")))
return response
def _doLogin(self):
'''
Go though the login process
'''
# First hit the login page to get our auth cookies set.
response = self._getBasicURI('')
# Our current cookies look okay? No need to login.
if str(response.url).endswith('/'):
return
# Perform the login POST.
print(textwrap.fill(textwrap.dedent("""\
You do not appear to have any valid login cookies set.
We will attempt to log you in with your Frontier
account, and cache your auth cookies for future use.
THIS WILL NOT STORE YOUR USER NAME AND PASSWORD.
""")))
print("\nYour auth cookies will be stored here:")
print("\n"+self._cookiefile+"\n")
print(textwrap.fill(textwrap.dedent("""\
It is advisable that you keep this file secret. It may
be possible to hijack your account with the information
it contains.
""")))
print(
"\nIf you are not comfortable with this, "
"DO NOT USE THIS TOOL."
)
print()
values = {}
values['email'] = input("User Name (email):")
values['password'] = getpass.getpass()
response = self._getBasicURI('user/login', values=values)
# If we end up being redirected back to login,
# the login failed.
if str(response.url).endswith('user/login'):
sys.exit('Login failed.')
# Check to see if we need to do the auth token dance.
if str(response.url).endswith('user/confirm'):
print()
print("A verification code should have been sent to your "
"email address.")
print("Please provide that code (case sensitive!)")
values = {}
values['code'] = input("Code:")
response = self._getBasicURI('user/confirm', values=values)
Vielen dank schon mal
Anhang anzeigen edapi.txt
(ist eine.py datei, aber man kann keine .py hochladen, daher.txt)
Zuletzt bearbeitet: