我正在编写一个自定义API包装器,用于在具有REST API的多个设备上自动化内容。对这些设备的身份验证是通过csrf令牌进行的。 我正在努力通过使用设备API作为自定义标记的表单输入建立连接。此外,我不确定这是否是启动此类项目的正确方法。
应用/ views.py
def index(request):
context = {}
template = loader.get_template('app/index.html')
return HttpResponse(template.render(context, request))
def webbase_html(request):
context = {}
load_template = request.path.split('/')[-1]
template = loader.get_template('app/' + load_template)
return HttpResponse(template.render(context, request))`
templatetags / device_handler.py
from django import template
register = template.Library()
from app.templatetags.device_api import DeviceAPI
from requests.exceptions import ConnectTimeout
@register.simple_tag
def login_device(host, username, password):
dev = DeviceAPI()
try:
dev.login(host, username, password)
hname = dev.get_host_name()
return hname
except ConnectTimeout as error:
return error
templatetags / device_api.py 看起来像这样:(代码段)
class DeviceAPI(object):
def __init__(self):
self._https = True
self._version = "Version is set when logged"
self._session = requests.session() # use single session
self._session.verify = False
def formatresponse(self, res):
resp = json.loads(res.content.decode('utf-8')
return resp
def update_cookie(self):
for cookie in self._session.cookies:
if cookie.name == 'ccsrftoken':
csrftoken = cookie.value[1:-1] # token stored as a list
self._session.headers.update({'X-CSRFTOKEN': csrftoken})
def login(self, host, username, password):
self.host = host
if self._https is True:
self.url_prefix = 'https://' + self.host
else:
self.url_prefix = 'http://' + self.host
url = self.url_prefix + '/logincheck'
res = self._session.post(
url,
data='username=' + username + '&secretpass=' + password + "&ajax=1", timeout=10)
if b"1document.location=\"/ng/prompt?viewOnly&redir" in res.content:
self.update_cookie()
else:
raise Exception('login failed')
模板/ connect.html
{% extends "app/base_site.html" %}
{% block title %} test {% endblock title %}
{% block stylesheets %}
{{ block.super }}
{% endblock stylesheets %}
{% block content %}
{% load my_class %}
<div class="right_col" role="main">
<h3>Connected to</h3>
<p>{% login_device "192.168.100.1" "user" "password" %}</p>
</div>
{% endblock content %}
{% block javascripts %}
{{ block.super}}
{% endblock javascripts %}
connect html将返回设备Hostname。但我怀疑这是一种合法的方法来进行这种REST交互。 所以我想知道与设备API交互的最佳做法是什么方法。
与此构造相关,如何使用输入表单以正确的方式调用login_device?