• python和web框架面试题目整理(3)


    1、django为什么需要缓存,有几种缓存方式?
    答:由于Django是动态网站,部分请求均会去数据库进行相应的操作,当程序的访问量大时,耗时必然会更加明显,最简单解决方式是使用缓存提高读请求的处理效率。总共有6种缓存方式。
    (1)搭建一个memcached服务器,监听在11211端口,然后在django所在机器上,安装一个python-memcached模块,在settings.py指定Cache字段中的Memcached守护进程的IP地址和端口,如果memcached安装在本机上面,那么也可以使用memcached的unix套接字。
    (2)创建数据库缓存表,在settings.py中指定后端存储的引擎和数据表名,然后执行python manage.py createcachetable,默认使用default数据库
    (3)基于文件系统的缓存,文件引擎会序列化各个缓存的值,将其存入指定的文件中
    (4)本地内存缓存,不适合生产环境
    (5)虚拟缓存,供开发调试,但它并不真正进行缓存,只是实现了缓存接口。
    参考文档:《精通django》
    https://www.cnblogs.com/LiCheng-/p/6920900.html

    2、django中如何上传文件?
    答:大体而言,一般有两种方式可以上传文件,分别是form表单提交到后台和通过ajax提交到后台
    (1)方式一:form表单上传到后台
    [root@k8s-master ~]# cat upload.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <form action="/upload/" method="post" enctype="multipart/form-data">
    <input type="file" name="fafafa">
    <input type="submit" value="提交">
    </form>
    </body>
    </html>

    [root@k8s-master ~]# cat forms.py
    class FileForm(forms.Form):
    ExcelFile = forms.FileField()

    [root@k8s-master ~]# cat models.py
    class UploadFile(models.model):
    userid = models.CharField(max_length=30)
    file = models.FileField(upload_to='./upload') # 在app下新建一个upload目录
    date = models.DateTimeField(auto_now_add=True)

    [root@k8s-master ~]# cat views.py
    from .forms import *

    def uploadFile(request):
    uf = forms.FileForm(request.POST,request.FILES) # 在视图中实例化forms.py的类
    if uf.is_valid():
    upload = models.UploadFile()
    upload.userid = 1
    upload.file = uf.cleaned_data['fafafa'] # fafafa是前端form表单中的文件name属性
    upload.save()
    print upload.file
    return render(request, 'upload.html', locals())

    方式二:通过ajax上传文件
    [root@k8s-master ~]# cat upload.html
    <!--添加文件模态窗-->
    <div class="widget-box">
    <div class="widget-title">
    <button style="float:right;" class="btn btn-primary btn-sm" id="addBtn">添加文件</button>
    </div> <!--widget-title end-->

    <div id="addModal" class="modal fade">
    <div class="modal-dialog">
    <div class="modal-content">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title">镜像上传</h4>
    </div><!--modal-header end-->

    <div class="modal-body">
    <form class="form-horizontal" id="addForm" accept-charset="UTF-8">
    <div class="control-group">
    <label class="control-label col-sm-4">请从本机添加文件:</label>
    <div class="col-sm-8">
    <input type="file" name="file" id="file_upload">
    </div>
    </div>

    <div class="form-group">
    <div class="modal-footer">
    <button class="btn btn-primary" id="submitbtn" >确认添加</button>
    <button class="btn btn-warning" data-dismiss="modal">退出</button>
    </div>
    </div>
    </form>
    </div><!-- /.modal-body-->
    </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
    </div>
    </div>

    <script src="/static/js/jquery-2.1.4.min.js"></script>
    <script>

    $("#addBtn").on('click',function(){
    $('#addModal').modal('show')
    });

    $("#submitbtn").click(function () {
    FileUpload()
    });

    function FileUpload() {
    var form_data = new FormData();
    var file_info =$('#file_upload')[0].files[0];
    form_data.append('file',file_info);
    //if(file_info==undefined)暂且不许要判断是否有附件
    //alert('你没有选择任何文件');
    //return false
    $.ajax({
    url:'/assets/upload/',
    type:'POST',
    data: form_data,
    processData: false, // tell jquery not to process the data
    contentType: false, // tell jquery not to set contentType
    success: function(callback) {
    swal({
    title:"success",
    text:"添加成功",
    type:"success",
    confirmButtonText:'确定'
    },function(){
    $('#addModal').modal('hide')
    window.location.reload();
    })
    }
    });
    }
    });

    </script>

    [root@k8s-master ~]# cat views.py
    from django.views.decorators.csrf import csrf_exempt

    @csrf_exempt
    def upload_ajax(request):
    if request.method == 'POST':
    file_obj = request.FILES.get('file') # 前端div中input标签的name属性
    path = '../../uploads/'
    import os
    if not os.path.exists(path):
    os.makedirs(path)
    f = open(path, 'wb') #可能需要使用r代表raw
    print(file_obj,type(file_obj))
    for chunk in file_obj.chunks():
    f.write(chunk)
    f.close()
    return render(request,'assets/index.html')
    参考文档:http://www.cnblogs.com/liyqiang/articles/7858523.html

    3、python2与python3有何区别?
    答:(1)print带不带括号问题
    (2)python3可以使用带有*号的变量,比如*x,y=[1,2,3]==>x=[1,2],y=3
    (3)input与raw_input
    (4)新式类与经典类

    4、如果一个可迭代对象的元素个数超过变量个数时,会抛出一个ValueError 。那么怎样才能从这个可迭代对象中解压出N个元素出来?
    答:使用星号表达式
    >>> lst = [1,2,3,(4,5)]
    >>> head,*middle,tail = lst
    >>> head
    1
    >>> middle
    [2,3]
    >>> tail
    (4,5)

    5、在一个文本打印具有'welcome'关键字样的前5行?
    答:保留有限历史记录正是collections.deque大显身手的时候。在写查询元素的代码时,通常会使用包含yield表达式的生成器函数,这样可以将搜索过程代码和使用搜索结果代码解耦。
    #coding: utf-8
    import sys
    from collections import deque

    def search(file_obj,pattern,history=5):
    prelines = deque(maxlen=history) # deque()是个类,本质是个队列,先进先出,history代表队列容量大小
    for line in file_obj:
    if pattern in line:
    yield line,prelines # 保留此次的结果值,除非调用一次函数,打印一次结果值
    prelines.append(line) # 打印没有匹配到模式的前五行,因为如果有之前行的,都会被删除,只会保留最新5行

    if __name__ == '__main__':
    with open(r'web.log.txt') as f:
    result = search(f,'welcome',5) # 过滤含有welcome字段的前5行,返回的是生成器
    for line,prelines in result: # 参考yield返回值,用来迭代
    for i in prelines:
    print i # 先打印前几行的内容
    print line # 打印关键字的当前行
    sys.exit()
    print '没有搜索到关键字!'

    参考文档:http://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p03_keep_last_n_items.html

    6、如何在一个列表或元组或集合中,快速搜素最大和最小的N个元素呢?字典中如何处理这样的含有数字的键值对呢?
    答:heapq模块能够很好的解决这类问题,返回的结果都是列表。heapq模块底层实现是堆排序(构造一个完全二叉树,父节点始终大于子节点)
    >>> import heapq
    列表:>>> lst = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    >>> print heapq.nsmallest(3,lst) # 这里的3代表N,前3个或后三个
    [-4, 1, 2]
    >>> print heapq.nlargest(3,lst)
    [42, 37, 23]

    元组:>>> tup = (1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2)
    >>> print heapq.nsmallest(3,tup)
    [-4, 1, 2]
    >>> print heapq.nlargest(3,tup)
    [42, 37, 23]
    >>>

    集合:>>> jihe = set([1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2])
    >>> print heapq.nsmallest(3,jihe)
    [-4, 1, 2]
    >>> print heapq.nlargest(3,jihe)
    [42, 37, 23]
    >>>

    字典:>>> profile = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    >>> print heapq.nsmallest(3,profile,key=lambda x:x['price'])
    >>> print heapq.nlargest(3,profile,key=lambda x:x['price'])
    参考文档:http://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p04_find_largest_or_smallest_n_items.html

    7、如何实现一个具有优先级的队列,队列优先级最高的元素将会率先弹出,优先级相同的元素,按照队列先入先出的方式进行弹出?
    答:heapq模块同样能实现队列,heappush和heappop来实现队列的插入和删除操作
    #coding: utf-8
    import heapq

    class PriorityQueue():
    def __init__(self):
    self._queue = []
    self._index = ()

    def push(self,item,priority):
    heapq.heappush(self._queue,(-priority,self._index,item))
    '''
    -priority代表从高到低进行排序,_index变量是为了比较相同优先级的元素,按照先进先出的方式弹出
    '''
    self._index += 1

    def pop(self):
    return heapq.heappop(self._queue)[-1] # heappop默认弹出最小的元素,-1是为了倒序弹出最大优先级的元素

    class Item():
    def __init__(self,name):
    self.name = name

    def __repr__(self): # __repr__方法是为了直接输出对象和print对象的时候,能够按照如下预定义的方式返回
    return 'Item(%s)' .format(self.name)
    -------------------------------------------------------
    >>> q = PriorityQueue()
    >>> q.push(Item('foo'), 1)
    >>> q.push(Item('bar'), 5)
    >>> q.push(Item('spam'), 4)
    >>> q.push(Item('grok'), 1)
    >>> q.pop()
    Item('bar')
    >>> q.pop()
    Item('spam')
    >>> q.pop() # 优先级相同,但是foo元素先入队列,所以先出
    Item('foo')
    >>> q.pop()
    Item('grok')
    >>>
    参考文档:http://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p05_implement_a_priority_queue.html

    8、字典有序不?如果无序,如何把它变成有序的呢?
    答:字典本身是午休的,可以通过collections模块的OrderDict类是一个字典的元素保持有序。
    #coding: utf-8
    import collections
    import json
    d = collections.OrderedDict()

    d['yhc'] = 1
    d['ly'] = 4
    d['lxx'] = 3
    d['zlx'] = 2

    >> print d
    print json.dumps(d)
    OrderedDict([('yhc', 1), ('ly', 4), ('lxx', 3), ('zlx', 2)])
    {"yhc": 1, "ly": 4, "lxx": 3, "zlx": 2}

    9、如何在一个列表中搜索是否含有或相似某个元素呢?
    答:
    #coding: utf-8
    import sys
    import urllib2
    import re

    def search_elem(lst,item):
    for line in lst:
    if re.findall(item, line):
    print line
    print '存在'
    sys.exit()
    print '不存在'

    lst = dir(urllib2)
    search_elem(lst,'request')

    10、python字典对象和json如何转换,它们之间有何区别?
    将字典{"a": 1, "b": "str", "c":[2, 3], "d":{"e": 4}}
    转化为如下格式:
    {
    "a": 1,
    "c": [
    2,
    3
    ],
    "b": "str",
    "d": {
    "e": 4
    }
    }
    答:(1)json.dumps是将字典对象转换为json,而json.loads是将json转换为字典对象
    (2)json本质上一种字符串,它是一种数据格式,而字典是python对象(数据结构),有众多的调用方法;
    (3)json的key值必须是双引号,而dict的key值可以是双引号,也可以使单引号
    import json

    d1 = {"a": 1, "b": "str", "c":[2, 3], "d":{"e": 4}}
    print type(d1)
    j1 = json.dumps(d1, indent=2) # indent=2代表子节点比父节点前多几个空格
    print type(j1)
    print j1
    >>> <type 'dict'>
    >>> <type 'str'>
    参考文档:https://blog.csdn.net/GitzLiu/article/details/54296971

    11、如何用前端展示远程远程服务器的日志信息?
    答:web框架依然使用django,源端通过websocket来发送日志到显示端,也可以从显示端去远程拉取。或者前端写一个js定时器,不断的发ajax请求到后台,每回取出一段日志
    [root@k8s-minion ~]# cat server.py
    #coding: utf-8

    '''
    pip install websocket-client
    '''

    users = set() # 连接进来的websocket客户端集合
    def chat(ws):
    user.add(ws)
    while True:
    msg = ws.receive() # 接收客户端的信息
    if msg:
    for u in users:
    user.send(msg) # 发送消息给所有客户端
    else:
    break
    users.remove(ws) # 如果有客户端断开连接,则踢出users集合

    [root@k8s-minion ~]# cat client.py
    #coding: utf-8

    import subprocess
    import time
    import urllib
    import os,sys

    collect_log = '/var/log/message'
    socket_server = 'www.socket.com' # 因为是从agent端推送数据,所以最好使用hosts或dns解析到显示端的IP地址
    uri = '/djangweb/log'
    cmd = '/usr/bin/tailf collect_log'
    url = "http://%s%s" %(socket_server,uri) # django监听的url,这里默认python manage.py runserver 0:80

    def send_log():
    if not os.path.exists(collect_log):
    sys.exit()
    try:
    res = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    print '正在发送数据至[%s]...' %url
    log_data = res.stdout.read().strip()
    data = {'log_data':json.dumps(log_data)}

    value = data.encode('utf-8')
    host_request = urllib.request.Request(url,value)
    response = urllib.request.urlopen(host_request)
    message = response.read().decode()
    print '返回结果:%s' %message
    except Exception as e:
    message = '发送失败'
    print '33[31;1m发送失败,%s33[0m' %e

    if __name__ == '__main__':
    send_log()

    [root@k8s-minion ~]# cat display_log.html # 这个页面的方面在django的urls.py和views.py自行定义
    <!--
    (1)页面大标题栏:远程日志显示工具。页面小标题栏:显示是哪个服务的日志信息
    (2)两个bootstrap按钮:用于日志的启动查看与停止查看
    (3)一个内容框,从而往前看日志,可用于直接查看最后500条日志记录,点击更多,可以查看前面的日志信息
    -->

    参考文档:https://www.linuxidc.com/Linux/2015-02/113356.htm

    12、如何对字典中的value元素进行排序,求最大值和最小值呢?
    如:d1 = {'b':2,'a':1,'c':3}
    答:zip函数是分别将两个可迭代的对象的元素组合成多个元组,然后构成一个新的列表。
    >>> zip(d1.values(),d1,keys()) # 首先进行key-value的反转,keys()和values()方法返回的是两个键和值组成的列表
    [(1, 'a'), (3, 'c'), (2, 'b')]
    >>> min(zip(d1.values(),d1.keys())) # 如果多个元素的键所对应的值相同,那么也只会返回一个元素,这个元素根据键大小
    (1, 'a')
    >>> max(zip(d1.values(),d1.keys()))
    (3, 'c')
    >>> sorted(zip(d1.values(),d1.keys())) # zip函数返回的是一个列表,可以利用内置函数sorted对它进行排序
    [(1, 'a'), (2, 'b'), (3, 'c')]

    13、Python如何消除文件的重复行,并直接打印出来?(subprocess调用shell命令,uniq -c命令能实现)
    答:思想还是采用集合方法。
    def del_duplicate_line(seq):
    seen = set()
    for item in seq: # item代表文件的每一行
    if item not in seen:
    yield item ## 执行到此,停止
    seen.add(item) ## 保留上一次item的结果,放到下一次运行

    def main(file):
    with open(file,'r') as f:
    for line in del_duplicate_line(f): # 返回的是一个生成器,用for循环迭代出来
    print line

    if __name__ == "__main__":
    file = 'service_conf.txt'
    main(file)

    14、统计列表中每个元素的出现次数,并且打印出现次数最多的3个?
    答:运用collections模块的Counter方法即可。Counter能处理字典和列表,同时还支持数学的加法,统计所有元素的出现次数
    #coding: utf-8
    from collections import Counter
    words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
    ]

    count = Counter(words)
    print '每个元素出现的次数是:%s' %count
    top_three = count.most_common(3)
    print '出现最多元素的前三名是:%s' %top_three

    >>> a = {'a':1,'b':2}
    >>> b = {'b':3,'c':4,'a':5}
    >>> Counter(a)
    Counter({'b': 2, 'a': 1})
    >>> Counter(b)
    Counter({'a': 5, 'c': 4, 'b': 3})
    >>> Counter(b)+Counter(a)
    Counter({'a': 6, 'b': 5, 'c': 4})

    15、在一个列表中,有数字元素和非数字元素,如何过滤出来所有数字元素,构成一个新的列表呢?
    答:列表推导式可以过滤部分元素,另外内置函数filter方法也能进行过滤,比如filter(函数名,序列名)
    #coding: utf-8
    lst = ['1', '2', '-3', '-', '4', 'N/A', '5']

    def is_int(values):
    try:
    x = int(values)
    return True
    except ValueError:
    return False

    res = list(filter(is_int,lst))
    print res
    >>> ['1', '2', '-3', '4', '5']

    此篇文章,还有25道题目,在我的面经中,详情看下面。

    我会持续更新面试题目,包括linux,前端(vue,jquery,css)、python、mysql和redis的面经题目,后期加入golang。可以加我qq 2093905919或者微信 18828004657,跟我聊聊。(注:可以分享一部分面试题目,觉得可以的话,剩下的全部面试题目

     

    多年经验,非常多而广的题目,适合突击面试复习,适合运维工程师,python工程师,运维开发,甚至前端开发(vue,asp,jquery)等等),需要打赏200元,绝对物超所值)

  • 相关阅读:
    Flask安装教程
    Django进阶(2)
    反编译源码
    Jmeter之Bean shell使用(一)
    接口测试基础(fiddler、postman的使用、python实现测试接口程序)
    Fiddler显示服务器IP的方法
    web测试与app测试的区别
    互联网产品接入支付功能如何测试?
    web测试中的测试点和测试方法总结
    使用JMeter建立接口测试
  • 原文地址:https://www.cnblogs.com/yue-hong/p/13029727.html
Copyright © 2020-2023  润新知