日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

pythonweb面试常见问题_python和web框架面试题目整理(3)

發布時間:2025/3/12 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pythonweb面试常见问题_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

Title

[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

添加文件

×

請從本機添加文件:

確認添加

退出

$("#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();

})

}

});

}

});

[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

>>>

>>>

參考文檔: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 '\033[31;1m發送失敗,%s\033[0m' %e

if __name__ == '__main__':

send_log()

[root@k8s-minion ~]# cat display_log.html # 這個頁面的方面在django的urls.py和views.py自行定義

參考文檔: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元,絕對物超所值)

總結

以上是生活随笔為你收集整理的pythonweb面试常见问题_python和web框架面试题目整理(3)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。