Commit f88b8747 authored by Štěpán Henek's avatar Štěpán Henek 🐻

Basic communication with backend implemented

* it can query pakon server via foris controller
* display results in a table (usig ajax)
* should be able to obtain data in json only (accroding to Accept header)
parent 35bf498d
This diff is collapsed.
# Foris pakon plugin
# Copyright (C) 2017 CZ.NIC, z. s. p. o. <https://www.nic.cz>
#
# Foris is distributed under the terms of GNU General Public License v3.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import bottle
import json
import os
from foris import fapi
from foris.config import ConfigPageMixin, add_config_page
from foris.config_handlers import BaseConfigHandler
from foris.plugins import ForisPlugin
from foris.state import current_state
from foris.utils.translators import gettext_dummy as gettext, ugettext as _
class PakonPluginConfigHandler(BaseConfigHandler):
userfriendly_title = gettext("pakon")
def get_form(self):
form = fapi.ForisForm("pakon", {})
form.add_section(name="pakon", title=_(self.userfriendly_title))
return form
class PakonPluginPage(ConfigPageMixin, PakonPluginConfigHandler):
menu_order = 81
template = "pakon/pakon.tpl"
userfriendly_title = gettext("Pakon")
def save(self, *args, **kwargs):
kwargs['no_messages'] = True # disable default messages
return super(PakonPluginPage, self).save(*args, **kwargs)
def _prepare_render_args(self, args):
args['PLUGIN_NAME'] = PakonPlugin.PLUGIN_NAME
args['PLUGIN_STYLES'] = PakonPlugin.PLUGIN_STYLES
args['PLUGIN_STATIC_SCRIPTS'] = PakonPlugin.PLUGIN_STATIC_SCRIPTS
args['PLUGIN_DYNAMIC_SCRIPTS'] = PakonPlugin.PLUGIN_DYNAMIC_SCRIPTS
args['query'] = json.dumps({})
data = current_state.backend.perform(
"pakon", "perform_query", {"query_data": args['query']})
args['results'] = self._prepare_data(data)
def render(self, **kwargs):
self._prepare_render_args(kwargs)
return super(PakonPluginPage, self).render(**kwargs)
def _prepare_data(self, data):
return json.loads(data["response_data"])
def call_ajax_action(self, action):
if action == "perform_query":
if bottle.request.method != 'POST':
raise bottle.HTTPError(404, "Wrong http method (only POST is allowed.")
query_data = bottle.request.POST.get('query', {})
data = current_state.backend.perform(
"pakon", "perform_query", {"query_data": query_data})
if "text/html" in bottle.request.headers["Accept"]:
return bottle.template(
"pakon/_results",
results=self._prepare_data(data),
)
else:
bottle.response.content_type = "application/json"
return data["response_data"]
raise ValueError("Unknown AJAX action.")
class PakonPlugin(ForisPlugin):
PLUGIN_NAME = "pakon"
DIRNAME = os.path.dirname(os.path.abspath(__file__))
PLUGIN_STYLES = [
"css/pakon.css"
]
PLUGIN_STATIC_SCRIPTS = [
]
PLUGIN_DYNAMIC_SCRIPTS = [
"pakon.js"
]
def __init__(self, app):
super(PakonPlugin, self).__init__(app)
add_config_page("pakon", PakonPluginPage, top_level=True)
#pakon-results
td, th
padding: 3px
th
text-align: center
font-weight: bold
Foris.update_pakon_data = function(data_type) {
$.ajax({
type: 'post',
url:'{{ url("config_ajax", page_name="pakon") }}',
data: {
action: "perform_query",
query: $("#field-query").val(),
csrf_token: $("#csrf-token").val()
},
dataType: data_type,
}).done(function(response, status, xhr) {
if (xhr.status == 200) {
$("#pakon-results").replaceWith(response); // replace the table
}
}).fail(function(xhr) {
if (xhr.responseJSON && xhr.responseJSON.loggedOut && xhr.responseJSON.loginUrl) {
window.location.replace(xhr.responseJSON.loginUrl);
return;
}
});
/*
$.post(
'{{ url("config_ajax", page_name="pakon") }}', {
action: "perform_query",
query: $("#field-query").val(),
csrf_token: $("#csrf-token").val()
}).done(function(response, status, xhr) {
if (xhr.status == 200) {
$("#pakon-results").replaceWith(response); // replace the table
}
})
.fail(function(xhr) {
if (xhr.responseJSON && xhr.responseJSON.loggedOut && xhr.responseJSON.loginUrl) {
window.location.replace(xhr.responseJSON.loginUrl);
return;
}
});
*/
};
Foris.WS["pakon"] = function(msg) {
// No notifications for pakon right now
};
$(document).ready(function() {
$("#pakon-query-trigger").click(function(e) {
e.preventDefault();
Foris.update_pakon_data("html")
});
});
<div id="pakon-results">
%if results:
<table id="pakon-results-table">
<tbody>
%for record in results:
<tr>
%for item in record:
<td>{{ item }}</td>
%end
</tr>
%end
</tbody>
</table>
%else:
<p>{{ trans("No results found.") }}</p>
%end
</div>
%rebase("config/base.tpl", **locals())
<div id="page-pakon-plugin" class="config-page">
%include("_messages.tpl")
<form action="{{ url("config_action", page_name="pakon", action="perform_query") }}" class="config-form" method="post">
<div class="row">
<label for="field-lan_ipaddr">Router IP address</label>
<input name="query" value="{{ query }}" type="text" id="field-query"/>
<input type="hidden" name="csrf_token" value="{{ get_csrf_token() }}" id="csrf-token">
</div>
<div class="row">
<button type="submit" name="action" id="pakon-query-trigger" value="query-trigger" class="button">{{ trans("Query") }}</button>
</div>
</form>
<h3>{{ trans("Results") }}</h3>
%include("pakon/_results.tpl", results=results)
</div>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment