Python: Accessing a web page with basic authentication

Here I’m demonstrating on how to access a web page with basic authentication in PYTHON code. This is very simple python code example using urllib2 module and no third party modules being used. 

Using this code you can access any web link from your code and get return data from that link. This is like web proxy call 


 

import urllib2

accessURL = ‘https://remoteserver.com/accesspage’
pwdmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwdmanager.add_password(None, accessURL, “username”, “password”)
authhandler = urllib2.HTTPBasicAuthHandler(pwdmanager)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
returnPage = urllib2.urlopen(accessURL).read()

print returnPage


You can also send data to that URL call and get return data if that link returns. 


 

import urllib2

accessURL = ‘https://remoteserver.com/accesspage’
pwdmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwdmanager.add_password(None, accessURL, “username”, “password”)
authhandler = urllib2.HTTPBasicAuthHandler(pwdmanager)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
requestdata = urllib.urlencode({‘FIRST_NAME’ : ‘Sumant’,’LAST_NAME’ : ‘Kuchipudi’})
responsedata = urllib2.urlopen(accessURL, data=requestdata).read()

print responsedata


 

I hope this helps you

Advertisements

Prepare Dynamic Query with Dictionary and Table name in Python logic

This post is basically showing a logic to prepare an UPDATE query (by seeing this you can make INSERT and DELETE queries though) .

The inputs are table name and the dictionary with column names are keys and values.

This logic creates the reference to the table name and use it in entire query like

BIO_DATA bd

or

ADDRESS_DATA ad

Make sure the tables words are appended with “_” as database table guidelines. If you want you can still follow your own style and change the delimiter “.” or so.

The dictionary must have the corresponding table columns as keys but the values may or may not contains. If the values are presented they will be attached directly to the columns like

bd.REG_ID=’1234′

If the values are empty, then dynamic keys will be added like, in future if you want to add the values later. (This my not use for your query)

bd.REG_ID=:RED_ID

The Dictionary looks like the following:

{‘BIO_DATA_ID’:”,’REG_ID’:’1234′,’GENDER_TYP_ID’:”,’SRC_TYP_ID’:”,’BIRTHDAY’:’19761201′}

Finally the query looks like the following

UPDATE IDM_PER_REG.BIO_DATA bd SET bd.REG_ID=’1234′,bd.GENDER_TYP_ID=:GENDER_TYP_ID, bd.BIO_DATA_ID=:BIO_DATA_ID, bd.BIRTHDAY=’19761201′

Check for the following code ..

Note:- Follow the intends as python’s code format structure.  I pasted the code directly here, but you need to care when you run this. I also pasted the image, so you can arrange your code properly by seeing that image. Link to Code Format Image

def updateQuery(self,tableName,valuesDict):
dynQry = "UPDATE "
dynQry += tableName+" "
tableRef = ""
try:
if(tableName.split(".")[1].index("_")>=-1):
tableWords = tableName.split(".")[1].split("_")
for i in range(len(tableWords)):
for letter in str(tableWords[i]).split():
tableRef += letter[0].lower()
except Exception:
for letter in str(tableName.split(".")[1]).split():
tableRef += letter[0].lower()
dynQry += tableRef+" SET "
if(valuesDict is not None):
valueDict = dict(valuesDict)
count = 0
for key,value in valueDict.iteritems():
count+=1
if (value is None or len(value)<=0):
if(count < valueDict.__len__()):
dynQry += tableRef+"."+key+"=:"+key+","
else:
dynQry += tableRef+"."+key+"=:"+key
else:
if(count < valueDict.__len__()):
dynQry += tableRef+"."+key+"='"+value+"',"
else:
dynQry += tableRef+"."+key+"='"+value+"'"

return dynQry
Comments please..!

Python: Changing the Dictionary Keys and values

Here is the post to update the Python’s Dictionary keys and values..

The following steps are for changing the Dictionary keys:

the logic is implemented in the following.

1) take the input of a dictionary which needs to modified the keys.

mainDict = {‘FSTN’:’sum’,’MIDL’:’k’,’ANAME’:’kuch’,’PSTA’:’A’,
‘DOB’:’20081215′,’JOBC’:’1234′}

2) create another dictionary which takes the keys as from the input dictionary (mainDict) keys and values as the what you wanted to replace keys.

keyMap = {‘FSTN’:’FIRST_NAME’,’ANAME’:’LAST_NAME’,’MIDL’:’MIDDLE_NAME’,’DOB’:’BIRTH_DAY’,
‘PSTA’:’STATUS’,’JOBC’:’JOB_CODE’}

3)create final dictionary and loop over the mainDict to replace the keys

changedDict = {}
for key, value in mainDict.items():
changedDict[keyMap[key]] = value

OR

changedDict= dict((keyMap[key], value) for (key, value) in idDict.items())

The following steps are for changing/deleting the Dictionary values:

1)take the input of a dictionary which needs to modified the values.

mainDict = {‘FSTN’:’sum’,’MIDL’:’k’,’ANAME’:’kuch’,’PSTA’:’A’,
‘DOB’:’20081215′,’JOBC’:’1234′}

2)add, delete, and change values in that dictionary

mainDict[“ROOM”] = “HARRIS”
del mainDict[“MIDL”]
mainDict[“JOBC”] = “4321”

I’ll be adding more details about Dictionaries in other post.