Python: Exception Handling and network programming

Source: Internet
Author: User
Tags sql error urlencode

 Exception Handling:
Exception handling to use try,except,else,finally, etc.
EG1:
dic={
"id": 1,
"Name": "Houning",
"Sex": "NV"
}
Choice=input (' Please enter the attribute you want to see: ')
Try: #异常处理要用到try
Print (Dic[choice]) #如果代码没有异常, output this code
Except Exception as E: #这个Exception能捕捉到所有的异常; Other types of exception words can be replaced, but other exception information (such as Keyerror) captures are relatively single
Print (' Out of the ordinary ', e) #python3这样用, E printed out is the exception information, out of the exception, will output E; can also write other, but generally write E
Except Keyerror as E: #有把握的情况下可以写针对性的异常信息
Print (' Input key error ')
else: #没有出异常的话, go else here, or you can not write
Print (' OK ')
Finally: #有没有出异常都会走finally; When you manipulate a database or file, you need to close it, use Finally, close the file or database after finally
Print (' over ')

Some common exception information:
Attributeerror: An attempt was made to access a property that an object does not have, such as foo.x, but Foo has no attribute x
IOError: Input/Output exception, usually cannot open file
Importerror: Unable to import module or package, usually path problem or name error
Indentationerror: Code not aligned correctly, syntax error
Indexerror: Subscript index is out of sequence boundary, e.g. X has only three elements, but tries to access X[3]
Keyerror: Attempting to access a key that does not exist in the dictionary
The keyboardinterrupt:ctrl+c was pressed
Nameerror: Using a variable that has not been assigned to an object
SyntaxError: Syntax error
TypeError: The incoming object type does not match the requirements
Unboundlocalerror: Attempts to access a local variable that is not yet set, typically because there is another variable with the same name outside of the code block
ValueError: Pass in a value that is not expected by the caller, even if the value is of the correct type

EG2:
Judging is not a decimal, with the exception only a few lines of code can be judged
def is_float (s):
Try
Float (s) #float方法是强制转换为小数类型
Except Exception as E:
Return False
Return True

To actively throw an exception:
def is_correct_sql (SQL):
sql_start=[' select ', ' Update ', ' Insert ', ' delete '
For start in Sql_start:
If Sql.startswith (start):
Return True
Else
Raise TypeError #用raise主动抛出TypeError这个异常; When SQL error occurs, the exception information is TypeError;
If the active exception is not caught in the called function, the active exception can be caught as soon as an exception occurs in the function called at its previous level.

Python network programming:
That is, Python operates the network, which is to open a Web site, or request an HTTP interface, using the Urllib module.
Urllib module is a standard module, directly import Urllib can, in Python3 inside only urllib module, in Python2 There are urllib module and URLLIB2 module.
urllib module:
From urllib.request import Urlopen
From Urllib.parse import Urlencode,quote,unquote
Import Urllib,json
Url= ' https://www.baidu.com '
Res=urlopen (URL). read (). Decode () #打开这个url, fetching data; decode () is converting bytes into strings
#urlopen (URL) This is the send GET request; Requests send GET request is Requests.get (' http://baidu.com ')

New_res=json.loads (RES) #把返回的list的json串转成python的list数据类型
Url2= ' Http://python.nnzhp.cn/reg '
data={
"username": "hahaha",
"passwd": "123456",
"C_PASSWD": "123456"
}
Param=urlencode (data) #这个可以把data字典里的key value is stitched together, i.e. username=hahaha&passwd=123456&c_passwd=123456
Print (Urlopen (Url2,param.encode ()). Read (). Decode ()) #这个是发post请求; encode () can turn a string into a byte type
Url3= ' http://python.nnzhp.cn/reg:/,. '
Print (quote (URL3)) #quote是把特殊字符转化成url编码, such as%3a%3d, etc.;
#unquote是把URL编码变成原来的特殊字符
Requests Module
#requests模块就是基于urllib模块开发的, more useful
Import requests
url4= ' https://www.baidu.com '
Requests.get (URL). text #发get请求; The text method returns a string type
Requests.get (URL). JSON () #返回的是json类型, with different return types in different cases
url5= "http://python.nnzhp.cn/reg?username=hn&passwd=123456"
Requests.post (URL5). Text #发key The POST request of the value entry, and the text can also be converted to JSON (), meaning ibid.
url6= "Http://python.nnzhp.cn/set_sites"
b==
"Site": "NNZHP",
"url": "Http://www.nnzhp.cn"
}
Requests.post (Url6,json=d). JSON () #发json串入参的post请求

#访问添加cookie的url
data={"userid": 1, "Money": 999}
cookie={"token": "token12345"}
Res=requests.post (Url,data,cookies=cookie). JSON () #括号里写data可以直接拼接; Specify cookies using the cookies parameter
Print (RES)
#访问添加header的url, with cookies
Head_url= ' Http://api.nnzhp.cn/getuser2 '
data={' userid ': 1}
header={' Content-type ': "Application/json"}
Res=requests.post (Head_url,data,headers=header). JSON ()
#访问上传文件的url
Up_url= ' Http://python.nnzhp.cn/upload '
Res=requests.post (up_url,files={' file_name ': Open (' a.py ')}). JSON ()
Print (RES)

Python: Exception Handling and network programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.