Python small function

Source: Internet
Author: User

Directory

1. Uploading Files

2. Verification Code

First, upload files

First look at the request. FILES:

Dictionary request. Each entry in FILES is a UploadFile object. The UploadFile object has the following methods:
1, Uploadfile.read ():
Read all uploaded data from the file. When the upload file is too large, you may run out of memory and use caution.
2, Uploadfile.multiple_chunks ():
If the upload file is large enough to be split into multiple parts read-in, returns True. By default, returns True when the upload file is greater than 2.5M. However, this value can be configured.
3, Uploadfile.chunks ():
Returns a chunked generator for uploading files. If Multiple_chunks () returns TRUE, you must use Chrunks () in the loop instead of Read (). In general, the direct use of chunks () on the line.
4. Uploadfile.name: File name for uploading files
5, Uplaodfile.size: File size of uploaded files (bytes)

Django Normal version upload

models.py

Class UploadFile (models. Model):    username =models. Charfield (max_length=50)    UploadFile = models. Filefield (upload_to= './static/') #指定的upload目录相对于根目录下media目录    def __str__ (self):        return Self.username

  

Index.html

<form method= "POST" enctype= "Multipart/form-data" >    <label> User name: </label><input type= "Text" Name= "username"/>    <label> files: </label><input type= "file" name= "UploadFile"/>    < Input type= "submit" value= "' Commit"/></form>

 

views.py

def index (Request):    if Request.method = = ' POST ':        un = Request. Post.get (' username ')        print (un)        f = Request. Files.get (' UploadFile ') # ' uploadfile ' matches the input name in the submission form, see GetList ()        filename = os.path.join (' static ', f.name)  #存放内容的目标文件        # 123 = Os.path.join (' static ', ' images ', filename.name) with        open (filename, ' WB ') as keys:            For chunk in F.chunks (): The #chunks () method splits the file into a block (<=2.5m) Iteration Object                keys.write (chunk)                #新数据表信息        models. UploadFile.objects.create (Username=un, Uploadfile=filename)        return httpresponse (filename + ' OK ')    return Render_to_response (' index.html ', {})

  

Django from upload

models.py

Class UploadFile (models. Model):    username =models. Charfield (max_length=50)    UploadFile = models. Filefield (upload_to= './static/') #指定的upload目录相对于根目录下media目录    def __str__ (self):        return Self.username

  

Mo.html

<form method= "POST" enctype= "Multipart/form-data" >{{uf.username}}{{Uf.uploadfile}}    <input type= " Submit "value=" ' Submission '/></form>

  

forms.py

From Django Import Formsclass uploadform (forms. Form):    username = forms. Charfield ()    uploadfile = forms. Filefield ()

  

views.py

DEF model (Request):    if Request.method = = ' POST ':        uf =forms. Uploadform (Request. Post,request. FILES)        if Uf.is_valid ():            username =uf.cleaned_data[' username ']            uploadfile=uf.cleaned_data[' UploadFile ']            u = models. UploadFile ()            u.username=username            u.uploadfile=uploadfile            u.save ()            return HttpResponse (' OK ')    uf = forms. Uploadform ()    return render_to_response (' mo.html ', {' UF ': uf})

  

Ajax upload File HTML file
    <div>        {{uf.uploadfile}}       <input type= "button" id= "Submitj" value= "commit"/>   </div>    <script src= "/static/jquery-2.1.4.min.js" ></script><script>    $ (' #submitj '). Bind ("click", function () {        var file = $ (' #id_uploadfile ') [0].files[0];        Console.log ("fff", file);        var form = new FormData ();        Form.append (' uploadfile ', file);         $.ajax ({                type: ' POST ',                URL: '/mo/',                data:form,                processdata:false,  //Tell JQuery don't to Process the data                Contenttype:false,  //Tell JQuery isn't to set ContentType                success:function (ARG) {                }            })    }) </script>

  

views.py
def uploadfile (Request):    print (Request. FILES)    uf = forms.uploadform (Request. POST, request. FILES)    print (Uf.is_valid ())    if Uf.is_valid ():        upoad = models. UploadFile ()        print (123234)        upoad.username = ' Alex '        upoad.uploadfile = uf.cleaned_data[' UploadFile ']        Upoad.save ()    return render (Request, ' ajax.html ', locals ())

 

forms.py
From Django Import Formsclass uploadform (forms. Form):    uploadfile = forms. Filefield ()

  

models.py
Class UploadFile (models. Model):    username =models. Charfield (max_length=50)    UploadFile = models. Filefield (upload_to= './static/') #指定的upload目录相对于根目录下media目录    def __str__ (self):        return Self.username

  

Second, Verification code views.py
Import ioimport osfrom django_code import check_codedef check_coder (Request):    Mstream = io. Bytesio ()    img, code = check_code.create_validate_code ()    img.save (Mstream, "GIF")    request.session[" Checkcode "] = code   # #写入session    print (Mstream.getvalue ())    return HttpResponse (Mstream.getvalue ())

  

check_code.py file

#!/usr/bin/env python#Coding:utf-8ImportRandom fromPILImportImage, Imagedraw, Imagefont, imagefilter_letter_cases="Abcdefghjkmnpqrstuvwxy"  #lowercase letters To remove i,l,o,z that may interfere_upper_cases = _letter_cases.upper ()#Uppercase Letters_numbers ="'. Join (Map (str, RANGE (3, 10)))#DigitalInit_chars ="'. Join ((_letter_cases, _upper_cases, _numbers))defCreate_validate_code (size= (120, 30), chars=Init_chars, Img_type="GIF", Mode="RGB", Bg_color= (255, 255, 255), Fg_color= (0, 0, 255), Font_size=18, Font_type="Monaco.ttf", Length=4, Draw_lines=True, N_line= (1, 2), Draw_points=True, Point_chance= 2):    " "@todo: Generate CAPTCHA image @param size: The size of the picture, format (wide, high), default to (+), @param chars: Allowed character set, format string @param img_type: Picture saved Format, default is GIF, optional gif,jpeg,tiff,png @param mode: Picture mode, default is RGB @param bg_color: Background color, default is white @param fg_color: foreground color, captcha character color , the default is blue #0000ff @param font_size: captcha font size @param font_type: captcha font, default to Ae_alarabiya.ttf @param length: Number of captcha characters @p Aram Draw_lines: Whether the interference line @param N_lines: The number range of interference lines, the format tuple, the default is (1, 2), only valid when Draw_lines is true @param draw_points: whether to draw the interference point @ param point_chance: Probability of disturbance point occurrence, size range [0] @return: [0]: PIL image instance @return: [1]: string in captcha picture" "width, height= Size#wide, Highimg = image.new (mode, size, Bg_color)#Create a graphicDraw = Imagedraw.draw (img)#Create a brush    defget_chars ():" "generates a string of the given length, returning the list format" "        returnrandom.sample (chars, length)defcreate_lines ():" "Draw Interference Lines" "Line_num= Random.randint (*n_line)#number of interfering lines         forIinchRange (line_num):#starting pointBegin = (Random.randint (0, size[0]), Random.randint (0, size[1]))            #End PointEnd = (Random.randint (0, size[0]), Random.randint (0, size[1]) draw.line ([begin, end], fill=(0, 0, 0))defcreate_points ():" "Draw Interference points" "Chance= min (max (0, Int (point_chance)))#size limit in [0, +]         forWinchRange (width): forHinchRange (height): tmp= Random.randint (0, 100)                ifTMP > 100-Chance:draw.point ((W, h), fill=(0, 0, 0))defcreate_strs ():" "plotting Captcha characters" "C_chars=get_chars () STRs='%s'%' '. Join (C_chars)#spaces are separated by a space before and after each characterFont=Imagefont.truetype (Font_type, font_size) font_width, Font_height=font.getsize (STRs) Draw.text (((Width-Font_width)/3, (height-font_height)/3), STRs, Font=font, fill=Fg_color)return "'. Join (C_chars)ifDraw_lines:create_lines ()ifdraw_points:create_points () STRs=create_strs ()#graphic Warp Parametersparams = [1-float (Random.randint (1, 2))/100, 0, 0, 0,1-float (Random.randint (1, 10))/100, Float (random.randint (1, 2))/500,              0.001, Float (random.randint (1, 2))/500] img= Img.transform (Size, image.perspective, params)#Creating Distortionsimg= Img.filter (Imagefilter.edge_enhance_more)#filter, Edge enhancement (threshold value)    returnIMG, STRs
View Code

File connection Monaco.ttf font file

http://www.gringod.com/2006/02/24/return-of-monacottf/

Python small function

Related Article

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.