如何从Flask中的外部Python脚本接收有效负载

时间:2015-07-02 15:39:16

标签: python flask

我试图找出我的索引页面如何监听并从我正在运行的另一个Python脚本接收有效负载。 Python脚本使用以下命令发送有效负载:

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'away-mentor-form',
    'enableAjaxValidation'=>true,
)); ?>

<p class="note">Fields with <span class="required">*</span> are required.</p>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo "Last-Name, First-Name"; ?><br/>

    <?php
    $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
        'name'=>'name_search',
        'value'=>$model->name_search,

        'source'=>Yii::app()->createUrl('/AwayMentor/FindUserName'),// <- path to controller which returns dynamic data
        // additional javascript options for the autocomplete plugin
        'options'=>array(
            'minLength'=>'1', // min chars to start search
            'select'=>'js:function(event, ui) { console.log(ui.item.id +":"+ui.item.value); }'
        ),
        'htmlOptions'=>array(
            'id'=>'name_search',
            'rel'=>'val',
        ),
    ));
    echo $form->error($model,'name_search'); ?>
</div>


<div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>

<?php $this->endWidget(); ?>

(现在的有效负载为requests.post("http://127.0.0.1:5000/", params=payload)

我需要在Flask方面做些什么来捕获(不需要将它存储在数据库中)它在一个变量中(可能是像payload = {"name":'Dave'}这样简单的东西)?

我的flask.g(我的模板现在看起来像这样):

index.html

我的<html> <head> <title>{{ location.mspace }} - Makerspace </title> </head> <body> <h1>Hello, {{ user.nickname }}!</h1> </body> </html> 看起来像这样:

views.py

但我想用我的其他Python脚本中的有效负载替换from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): location = {'mspace': 'Central Library'} user = {'nickname': 'David'} return render_template('index.html', location = location, user = user)

1 个答案:

答案 0 :(得分:0)

使用request对象形式Flask,您可以从帖子请求中获取数据:

from flask import request

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    location = {'mspace': 'Central Library'}
    user = {'nickname': request.data.get('name', some_default)}
    return render_template('index.html',
                            location = location,
                            user = user)

或者,如果您想要做一些不同的事情,无论是POST还是GET,您的观点都应该是这样的。

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # do some stuff
    else:
        # do some other stuff