Python Web development framework-Django (2), python-django
Next, I will introduce some practical skills and notes. The first time I used MarkDown for editing, I felt that the gap was too large and not so nice.
GET/POST
Data Interaction between the front and back ends. JQuery is used to implement get/post requests.
GET
Method 1: Use a regular expression to match url parameters
$. Ajax ({type: "GET", url: "/search/serviceInfo/" + $ ('# servicename '). val () + "/", dataType: 'json', // expected data type returned by the server. I like to use json. Of course, you can use success such as xml/text/responseXML: function (msg) {// obtain the data returned by the server var logNames = msg ['logname']; // read the json field document. getElementById ('logs '). innerHTML = logNames ;},});
To pass parameters through the url path, you need to configure urls. py.
//urls.pyurlpatterns = patterns('', (r'^search/serviceInfo/(.+)/$', 'searchText.getServiceInfo'),)//searchText.pydef getServiceInfo(request, servicename): result = {} //something about servicename return HttpResponse(json.dumps(result))
Method 2: request parameter
//. Ajax same as the url: "/search/searchLog /? Offset = "+ tmpOffset +" & count = "+ pageCount // obtain parameters in the background. View function def searchLog (request): offset = request. GET. get ('offset '); count = request. GET. get ('Count'); // something
POST
Usually post is used to submit forms or upload data.
// Front-end jslogConf ={}; // something $. ajax ({type: "POST", url: "/setting/updschema/", data: JSON. stringify (logConf), ype: 'json', success: function (msg) {// something}); // background py receives def addSchema (request): conf = json. loads (request. body) # converts Chinese characters. The front-end data is in unicode format and needs to be transcoded once. servicename = conf ["servicename"]. encode ('utf8') logSchema. fields = json. dumps (conf ['fields']) logSchema. monitorLines = json. dumps (conf ['lines']) // something...
Conversion of json objects and strings: In js and python, json objects correspond to dictionaries and sequences, various scripting languages provide methods for converting strings into dictionary/sequence objects and converting objects into json strings.
// JsJSON. stringify (obj) converts JSON into a string JSON. parse (string) converts a string into a JSON object // pythonjson. convert dumps (obj) JSON to string json. convert the loads (str) string to JSON
CSRF: Cross Site Request Forgery Cross-Site Request Forgery. To ensure the authenticity of the Request, django provides a method to prevent csrf attacks. In post, the Request must carry the csrf token. Therefore, a csrf error occurs when post is used and the request is rejected. For the formal solution, see django csrf protection.
Web services provided by background programmers are mostly used internally and provide a method to bypass csrf. Modify settings. py to disable csrf verification, as shown below:
MIDDLEWARE_CLASSES = (//... comment out the following line # 'django. middleware. csrf. CsrfViewMiddleware ',//....)
Data Return
// Return the page or json data at the backend # return the new page return render_to_response('current_datetime.html ') # return the json data. The result is a dictionary return HttpResponse (json. dumps (result ))
Log usage
Set log in settings. py
Import loggingfrom logging. handlers import * from logging import Formatterroot = logging. getLogger () if len (root. handlers) = 0: # Log Path filename = OS. path. join (BASE_DIR, 'Log/tulip. log '). replace ('\', '/') # log format = '% (asctime) s % (levelname) s % (module) s. % (funcName) s Line: % (lineno) d % (message) s' # archive switch rotate = TimedRotatingFileHandler (filename, "midnight",) fmt = Formatter (format) rotate. setFormatter (fmt) root. addHandler (rotate) # log level, the following debug and above will show root. setLevel (logging. DEBUG)
Log can be directly used in python in the background:
import logginglogging.info(str)logging.debug(str)logging.warn(str)#....
Front end
Template: Search for bootstrap templates. You can see many beautiful and concise front-end templates.
Jquery:
// Style management $ ('# servicenameerr '). addClass ('has-error'); $ ('# servicenameerr '). removeClass ('has-error'); // value: servicename = $ ('# servicename '). val (); // ajax $. ajax ({});
Html dom:
// Clear the selector option, which is very simple. getElementById ("logName "). length = 0; // Delete document from a table row. getElementById ('fieldtable '). deleteRow (index); // Add row = document to table rows. getElementById ('fieldtable '). insertRow (index); row. innerHTML = "xxx"; // traverse the table var fieldRows = document. getElementById ('fieldtable '). rows; for (var I = 1; I <fieldRows. length; ++ I) {var cells = fieldRows [I]. cells; name = cells [0]. childNodes [0]. value; // There is an input control in the cell} // set the control content document. getElementById ('xxx '). innerHTML = ""; // The document can contain html tags. getElementById ('xxx '). innerText = ""; // plain text
A beautiful alert-toastr:
Toastr. options ['positionclass'] = 'toast-top-Center'; toastr. options ['timeout'] = "1000"; toastr. success ('configured successfully ');
A handy calendar control-My97DatePicker
// Indicates the calendar call, date format, and value restriction in onclick. <script language = "javascript" type = "text/javascript" src = "/static/My97DatePicker/WdatePicker. js "> </script> <input id =" startTime "type =" text "placeholder =" Start Time "onClick =" WdatePicker ({dateFmt: 'yyyy-MM-dd HH: mm: ss', maxDate: '# F {$ dp. $ D (\ 'endtime \')}'}) "/> <input id =" endTime "type =" text "placeholder =" End Time "onClick =" WdatePicker ({dateFmt: 'yyyy-MM-dd HH: mm: ss', minDate: '# F {$ dp. $ D (\ 'starttime \ ')}'}) "/>
References
Django book: http://djangobook.py3k.cn/2.0/
Download Django: https://www.djangoproject.com/download/
Bootstrap front-end framework: http://www.bootcss.com/
JQuery: http://www.w3school.com.cn/jquery/
Html dom: http://www.w3school.com.cn/htmldom/
Toastr: https://github.com/CodeSeven/toastr
My97DatePicker: http://www.my97.net/
Django csrf: https://docs.djangoproject.com/en/dev/ref/csrf