How to unify Pyramid Python views to handle Ajax / html POST addresses

I have some HTML forms in a Python Pyramid application. I would like them to work through AJAX when JavaScript is enabled and when JavaScript is disabled. Now I use different views for AJAX messages and the regular form, but for these functions the code seems almost the same except for the answer. I use a view class (this body):

def ajax_ok(self, msg):
    return Response(body=msg)

def ajax_error(self, msg):
    return HTTPInternalServerError(body=msg)

@action(xhr=True, renderer='json', name='ftp')
def ftp_ajax(self):
    log.debug('View: %s', 'ftp (ajax)')
    if 'form.submitted' in self.params:
        try:
            self.config.save(self.params)
        except:
            return self.ajax_error('some error')
        else:
            return self.ajax_ok('ok')

@action()
def ftp(self):
    if 'form.submitted' in self.params:
        try:
            self.config.save(self.params)
        except:
            self.request.session.flash('error; ' + msg)
        else:
            self.request.session.flash('success; ' + msg)
    return {'content': render('templates/ftp.pt', {'ftp':
                                                    self.config.ftp})} 

I need to handle errors, if any, and display them in html. Maybe I should use finished_callback or my own renderer, which will send different responses for different types of requests?

+5
source share
2 answers

You can do something like this:

@action(name='ftp', renderer='templates/ftp.pt')
@action(xhr=True, renderer='json', name='ftp')
def ftp_ajax(self):
    log.debug('View: %s', 'ftp (ajax)')

    # CODE

    if request.is_xhr:
        return JSON
    else:
        return something for template

, - :

@action(name='ftp', renderer='templates/ftp.pt')
@action(xhr=True, renderer='json', name='ftp')
def ftp_ajax(self):
    log.debug('View: %s', 'ftp (ajax)')
    my_values = dict()

    # Code

    return my_values

, , , , , - , .

, . , @action .

+4

ftp, , request.is_xhr , /.

0

All Articles