Django -如何在模板中调用带参数的函数

ecfdbz9o  于 2022-12-01  发布在  Go
关注(0)|答案(3)|浏览(153)

我有以下基于函数的视图:

def get_emails(request, HOST, USERNAME, PASSWORD):
    context = {
        'FU_HOST': settings.FU_HOST,
        'FU_USERNAME': settings.FU_USERNAME,
        'FU_PASSWORD': settings.FU_PASSWORD,
        'FV_HOST': settings.FV_HOST,
        'FV_USERNAME': settings.FV_USERNAME,
        'FV_PASSWORD': settings.FV_PASSWORD,
        'USV_HOST': settings.USV_HOST,
        'USV_USERNAME': settings.USV_USERNAME,
        'USV_PASSWORD': settings.USV_PASSWORD,
    }
    m = imaplib.IMAP4_SSL(HOST, 993)
    m.login(USERNAME, PASSWORD)
    m.select('INBOX')
    result, data = m.uid('search', None, "ALL")
    if result == 'OK':
        for num in data[0].split():
            result, data = m.uid('fetch', num, '(RFC822)')
            if result == 'OK':
                email_message_raw = email.message_from_bytes(data[0][1])
                email_from = str(make_header(decode_header(email_message_raw['From'])))
                email_addr = email_from.replace('<', '>').split('>')
                if len(email_addr) > 1:
                    new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X')
                    new_entry.save()
                else:
                    new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X')
                    new_entry.save()
    m.close()
    m.logout()

    messages.success(request, f'Subscribers list sychronized successfully.')
    return redirect('subscribers')

我想在我的前端上放置3个按钮,每次使用不同的参数调用同一个函数,例如一个按钮get_emails(FU_HOST,FU_USERNAME,FU_PASSWORD),另一个按钮get_emails(USV_HOST,USV_USERNAME,USV_PASSWORD)。
在Django中如何实现这一点?我的证书存储在.env文件中。

vtwuwzda

vtwuwzda1#

这样的事情并不是通过将该函数放在前端模板上来实现的,您需要做的是将用户重定向到包含该函数的视图,并从用户请求中提取这些值,因为正如您所看到的,您有一些方法正在访问您的数据库,这不是您可以从前端实现的事情,如果可能的话也是不安全的。

mnemlml8

mnemlml82#

从上下文中我可以理解传递给函数的参数必须是安全的。
因此,使用如下POST表单:

def get_emails(request):
    context = {
        'FU_HOST': settings.FU_HOST,
        'FU_USERNAME': settings.FU_USERNAME,
        'FU_PASSWORD': settings.FU_PASSWORD,
        'FV_HOST': settings.FV_HOST,
        'FV_USERNAME': settings.FV_USERNAME,
        'FV_PASSWORD': settings.FV_PASSWORD,
        'USV_HOST': settings.USV_HOST,
        'USV_USERNAME': settings.USV_USERNAME,
        'USV_PASSWORD': settings.USV_PASSWORD,
    }

    if request.method == "POST":
        HOST = request.POST["HOST"]
        USERNAME = request.POST["USERNAME"]
        PASSWORD = request.POST["PASSWORD"]

        m = imaplib.IMAP4_SSL(HOST, 993)
        m.login(USERNAME, PASSWORD)
        m.select('INBOX')
        result, data = m.uid('search', None, "ALL")
        if result == 'OK':
            for num in data[0].split():
                result, data = m.uid('fetch', num, '(RFC822)')
                if result == 'OK':
                    email_message_raw = email.message_from_bytes(data[0][1])
                    email_from = str(make_header(decode_header(email_message_raw['From'])))
                    email_addr = email_from.replace('<', '>').split('>')
                    if len(email_addr) > 1:
                        new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X')
                        new_entry.save()
                    else:
                        new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X')
                        new_entry.save()
        m.close()
        m.logout()

        messages.success(request, f'Subscribers list sychronized successfully.')
        return redirect('subscribers')

在模板中,发出post请求,给定主机、用户名和密码,如下所示。

<form action="{% url 'name-of-your-view' %}" method="POST">
<input type="text" name="HOST">
<input type="text" name="USERNAME">
<input type="text" name="PASSWORD">
<input type="submit">
</form>
093gszye

093gszye3#

对于这个场景,如果Form Post方法不适合您,您可以使用JavaScript和Ajax。
将以下代码添加到html代码中以使用javascript方法。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
    function post(_host,_username,_password){
        $.ajax({
            url: '{% url "url-name"%}',
            type: 'POST',
            data: { 
                csrfmiddlewaretoken: "{{ csrf_token }}",
                host: _host,
                username = _username,
                password = _password
            },
            success: function (res) {
                console.log(res);
            }
        });
    }
</script>

更新python函数,如下所示。

def get_emails(request):
    HOST = request.POST.get('host')
    USERNAME = request.POST.get('username')
    PASSWORD = request.POST.get('password')
    context = {
        'FU_HOST': settings.FU_HOST,
        'FU_USERNAME': settings.FU_USERNAME,
        'FU_PASSWORD': settings.FU_PASSWORD,
        'FV_HOST': settings.FV_HOST,
        'FV_USERNAME': settings.FV_USERNAME,
        'FV_PASSWORD': settings.FV_PASSWORD,
        'USV_HOST': settings.USV_HOST,
        'USV_USERNAME': settings.USV_USERNAME,
        'USV_PASSWORD': settings.USV_PASSWORD,
    }
    m = imaplib.IMAP4_SSL(HOST, 993)
    m.login(USERNAME, PASSWORD)
    m.select('INBOX')
    result, data = m.uid('search', None, "ALL")
    if result == 'OK':
        for num in data[0].split():
            result, data = m.uid('fetch', num, '(RFC822)')
            if result == 'OK':
                email_message_raw = email.message_from_bytes(data[0][1])
                email_from = str(make_header(decode_header(email_message_raw['From'])))
                email_addr = email_from.replace('<', '>').split('>')
                if len(email_addr) > 1:
                    new_entry = EmailMarketing(email_address=email_addr[1], mail_server='X')
                    new_entry.save()
                else:
                    new_entry = EmailMarketing(email_address=email_addr[0], mail_server='X')
                    new_entry.save()
    m.close()
    m.logout()

    messages.success(request, f'Subscribers list sychronized successfully.')
    return redirect('subscribers')

希望能帮上忙。

相关问题