视觉中国官网,柳州做网站优化,手机网站首页怎么做,wordpress 查看访客1、django为什么需要缓存#xff0c;有几种缓存方式#xff1f;答#xff1a;由于Django是动态网站#xff0c;部分请求均会去数据库进行相应的操作#xff0c;当程序的访问量大时#xff0c;耗时必然会更加明显#xff0c;最简单解决方式是使用缓存提高读请求的处理效率…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.html2、django中如何上传文件答大体而言一般有两种方式可以上传文件分别是form表单提交到后台和通过ajax提交到后台(1)方式一form表单上传到后台[rootk8s-master ~]# cat upload.htmlTitle[rootk8s-master ~]# cat forms.pyclass FileForm(forms.Form):ExcelFile forms.FileField()[rootk8s-master ~]# cat models.pyclass UploadFile(models.model):userid models.CharField(max_length30)file models.FileField(upload_to./upload) # 在app下新建一个upload目录date models.DateTimeField(auto_now_addTrue)[rootk8s-master ~]# cat views.pyfrom .forms import *def uploadFile(request):uf forms.FileForm(request.POST,request.FILES) # 在视图中实例化forms.py的类if uf.is_valid():upload models.UploadFile()upload.userid 1upload.file uf.cleaned_data[fafafa] # fafafa是前端form表单中的文件name属性upload.save()print upload.filereturn render(request, upload.html, locals())方式二通过ajax上传文件[rootk8s-master ~]# cat upload.html添加文件 ×镜像上传请从本机添加文件确认添加退出$(#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_infoundefined)暂且不许要判断是否有附件//alert(你没有选择任何文件);//return false$.ajax({url:/assets/upload/,type:POST,data: form_data,processData: false, // tell jquery not to process the datacontentType: false, // tell jquery not to set contentTypesuccess: function(callback) {swal({title:success,text:添加成功,type:success,confirmButtonText:确定},function(){$(#addModal).modal(hide)window.location.reload();})}});}});[rootk8s-master ~]# cat views.pyfrom django.views.decorators.csrf import csrf_exemptcsrf_exemptdef upload_ajax(request):if request.method POST:file_obj request.FILES.get(file) # 前端div中input标签的name属性path ../../uploads/import osif not os.path.exists(path):os.makedirs(path)f open(path, wb) #可能需要使用r代表rawprint(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.html3、python2与python3有何区别答(1)print带不带括号问题(2)python3可以使用带有*号的变量比如*x,y[1,2,3]x[1,2],y3(3)input与raw_input(4)新式类与经典类4、如果一个可迭代对象的元素个数超过变量个数时会抛出一个ValueError 。那么怎样才能从这个可迭代对象中解压出N个元素出来答使用星号表达式 lst [1,2,3,(4,5)] head,*middle,tail lst head1 middle[2,3] tail(4,5)5、在一个文本打印具有welcome关键字样的前5行答保留有限历史记录正是collections.deque大显身手的时候。在写查询元素的代码时通常会使用包含yield表达式的生成器函数这样可以将搜索过程代码和使用搜索结果代码解耦。#coding: utf-8import sysfrom collections import dequedef search(file_obj,pattern,history5):prelines deque(maxlenhistory) # deque()是个类本质是个队列先进先出history代表队列容量大小for line in file_obj:if pattern in line:yield line,prelines # 保留此次的结果值除非调用一次函数打印一次结果值prelines.append(line) # 打印没有匹配到模式的前五行因为如果有之前行的都会被删除只会保留最新5行if __name__ __main__:with open(rweb.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.html6、如何在一个列表或元组或集合中快速搜素最大和最小的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,keylambda x:x[price]) print heapq.nlargest(3,profile,keylambda x:x[price])参考文档http://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p04_find_largest_or_smallest_n_items.html7、如何实现一个具有优先级的队列队列优先级最高的元素将会率先弹出优先级相同的元素按照队列先入先出的方式进行弹出答heapq模块同样能实现队列heappush和heappop来实现队列的插入和删除操作#coding: utf-8import heapqclass 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 1def pop(self):return heapq.heappop(self._queue)[-1] # heappop默认弹出最小的元素-1是为了倒序弹出最大优先级的元素class Item():def __init__(self,name):self.name namedef __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.html8、字典有序不如果无序如何把它变成有序的呢答字典本身是午休的可以通过collections模块的OrderDict类是一个字典的元素保持有序。#coding: utf-8import collectionsimport jsond collections.OrderedDict()d[yhc] 1d[ly] 4d[lxx] 3d[zlx] 2 print dprint json.dumps(d)OrderedDict([(yhc, 1), (ly, 4), (lxx, 3), (zlx, 2)]){yhc: 1, ly: 4, lxx: 3, zlx: 2}9、如何在一个列表中搜索是否含有或相似某个元素呢答#coding: utf-8import sysimport urllib2import redef search_elem(lst,item):for line in lst:if re.findall(item, line):print lineprint 存在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 jsond1 {a: 1, b: str, c:[2, 3], d:{e: 4}}print type(d1)j1 json.dumps(d1, indent2) # indent2代表子节点比父节点前多几个空格print type(j1)print j1 参考文档https://blog.csdn.net/GitzLiu/article/details/5429697111、如何用前端展示远程远程服务器的日志信息答web框架依然使用django源端通过websocket来发送日志到显示端也可以从显示端去远程拉取。或者前端写一个js定时器不断的发ajax请求到后台每回取出一段日志[rootk8s-minion ~]# cat server.py#coding: utf-8pip install websocket-clientusers set() # 连接进来的websocket客户端集合def chat(ws):user.add(ws)while True:msg ws.receive() # 接收客户端的信息if msg:for u in users:user.send(msg) # 发送消息给所有客户端else:breakusers.remove(ws) # 如果有客户端断开连接则踢出users集合[rootk8s-minion ~]# cat client.py#coding: utf-8import subprocessimport timeimport urllibimport os,syscollect_log /var/log/messagesocket_server www.socket.com # 因为是从agent端推送数据所以最好使用hosts或dns解析到显示端的IP地址uri /djangweb/logcmd /usr/bin/tailf collect_logurl http://%s%s %(socket_server,uri) # django监听的url这里默认python manage.py runserver 0:80def send_log():if not os.path.exists(collect_log):sys.exit()try:res subprocess.Popen(cmd,stdoutsubprocess.PIPE,stderrsubprocess.PIPE,shellTrue)print 正在发送数据至[%s]... %urllog_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 %messageexcept Exception as e:message 发送失败print \033[31;1m发送失败%s\033[0m %eif __name__ __main__:send_log()[rootk8s-minion ~]# cat display_log.html # 这个页面的方面在django的urls.py和views.py自行定义参考文档https://www.linuxidc.com/Linux/2015-02/113356.htm12、如何对字典中的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 lineif __name__ __main__:file service_conf.txtmain(file)14、统计列表中每个元素的出现次数并且打印出现次数最多的3个答运用collections模块的Counter方法即可。Counter能处理字典和列表同时还支持数学的加法统计所有元素的出现次数#coding: utf-8from collections import Counterwords [look, into, my, eyes, look, into, my, eyes,the, eyes, the, eyes, the, eyes, not, around, the,eyes, dont, look, around, the, eyes, look, into,my, eyes, youre, under]count Counter(words)print 每个元素出现的次数是%s %counttop_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-8lst [1, 2, -3, -, 4, N/A, 5]def is_int(values):try:x int(values)return Trueexcept ValueError:return Falseres 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元绝对物超所值)