web2py with js framework

1,046 views
Skip to first unread message

黄祥

unread,
Aug 8, 2017, 8:54:12 PM8/8/17
to web2py-users
is there any simple web2py app with js framework (whatever) that have a CRUD or GRID example?
want to learn to combine it, but confuse, what is web2py job (define models, provide restful api, any others ?), what is js framework job (client side response) ? how about the form handling (web2py or js job?)
some of dev in here talk about vuejs, so i just look at it and learn from the example
https://vuejs.org/v2/examples/grid-component.html

but again, don't know how to connect it with web2py, any hints or example maybe.

thanks and best regards,
stifan

Anthony

unread,
Aug 8, 2017, 8:58:18 PM8/8/17
to web2py-users

黄祥

unread,
Aug 8, 2017, 10:24:18 PM8/8/17
to web2py-users
thanks for reference anthony, already seen and learned from web2py scaffold (vue + whoosh) but for me, it's complex
i want to learn it start from simple first, perhaps there is another simple web2py app with whatever js framework (1 table with 1 field that have CRUD operation or GRID is enough to know web2py job's part and js framework jobs part)

Mirek Zvolský

unread,
Aug 9, 2017, 6:53:49 AM8/9/17
to web2py-users
This is not so much complex if you split it into 2 steps.

1) Be familiar with the welcome/ application - this is scaffold application in standard web2py distribution.

- Models are called always and create db (database object and sql database structures) + auth (authorization object) + menu.
- Controller is called based on url, example: app/default/index will call function index() in app/controllers/default.py
- If controller will return dictionary {'key1': val1, 'key2': val2, ...} it is rendered on the server side with template (=view) like app/views/default/index.html
  {{=key1}} will output variable from controller somewhere into html.

app/controllers/default.py func user() + app/views/default/user.html is for authorizetion, login,..
app/controllers/appadmin is for view and manage database data (you can use some standard database manager instead)

2) Now you can see that in github.com/web2py/scaffold is almost nothing added. Just client side (javascript from static/js/) is made with vue.js.

+ see the controller main() in default.py (it gives no data at all to the template) and the template app/views/default/main.html

In html:
{{=....}} are included on server side by web2py
${...} are for client side, vue.js

--------------
Of course you can
- remove full text search whoosh to make things easier
- replace stupid.css with your own css or with bootstrap
- replace vue.js with react or something easier: preact or inferno





Dne středa 9. srpna 2017 4:24:18 UTC+2 黄祥 napsal(a):

Val K

unread,
Aug 12, 2017, 12:35:19 PM8/12/17
to web2py-users
Hi, Stifan!

What do you mean by "combine"? Are you ready to migrate to SPA or just want to make some awesome components to replace native web2py ones, but staying with client-server-ping-pong-logic? The latter is much easier (to connect with web2py you need only ajax request to get records, then they could be passed to vue-component by overwriting  demo.gridData -  just for exmpl), but the first is more perspective. So, what do you want?

Ben Lawrence

unread,
Aug 12, 2017, 1:31:53 PM8/12/17
to web2py-users
If you use that scaffold, it needs vue version 1. Current version of vue is version 2.something.

黄祥

unread,
Aug 12, 2017, 10:38:35 PM8/12/17
to web2py-users
@ mirek
thanks for the pointer, that's what i learned from scaffold app, need to remove the unnecessary thing like whoosh, so that i can focus to learn the logic what job is handle by whom (web2py or js framework), need to learn start from simplest first, hehe

@ val
just want to learn how can web2py work together with js framework, is it web2py job just send the (json format) to the js framework with web service
ref

@ben
yeah, i realize it, but during the learning, i just want to keep focus what i got (scaffold app), after i underrstand, perhaps can migrate to version 2.something

Carlos Kitu

unread,
Aug 14, 2017, 2:56:46 AM8/14/17
to web2py-users
Hi stifan,
I just wanted to share my recent experience with vue.js and web2py.
At first I didn't want to give up things like sqlform.
Then I tried to tweak the form generated by web2py with el1=form.element(...) to get a reference to the html element I wanted to add certain vue.js directives like v-if, v-model, ...
It was so easy as:
el1["_v-if"]="something"

It works but later I realized that it was not practical because I the logic spread between the controller, with the form generation, and vue.js directives, then the html view where I had more vue.js directives and components, and the main js vue controller.

As I didn't want to renounce to the look and feel of web2py, because I just needed a very dynamic function made in vue, and the rest of the application could be made the traditional way with web2py, I resorted to generating just once the form with web2py and copying manually the resulting html code to the html view, and that way I just have to work with the html view and the JS code as usual in vue.js apps.
With regard to passing data from the controller to vue.js, you can use {{=ASSIGNJS(key1=val1, key2=val2, ...)}} in your view and you will get those keys available as global vars in JavaScript with the needed translations to JSON in case you use complex values as lists, dicts, ...

If anybody found a better way to integrate the things, please let us know.

Hope this helps.
Best regards.

黄祥

unread,
Aug 14, 2017, 6:09:57 AM8/14/17
to web2py-users
thanks Carlos for the clear hints

best regards,
stifan

Limedrop

unread,
Aug 15, 2017, 1:23:34 AM8/15/17
to web2py-users
@Carlos...I don't know if this is better, but it is different.  Probably more suited to bigger apps.  My basic assumption is that if you're going to use vue.js then, ultimately, it will be a lot easier if you stick to the proper vue.js way of doing things.  In general this means letting vue.js do it's stuff with the frontend and leaving web2py with the data and backend.

Specifically it means setting up your view files like this:

And using this:

In development mode I have web2py running on one port and node running on another (node's hot-reloading seems like magic, and you can use the chrome VueDevtools plugin to debug). When I'm ready to commit I run "npm run build".  The index file is then compiled to "/views/default/index.html", and the assets are compiled to "/static".

In production I get web2py to serve the index file and then get vue.js to load whatever else it needs via ajax (axios).

A basic outline of the key files are given below.  Note that these are just snippets to show you how you might do it...the code is incomplete and it will NOT work out-of-the-box.


====\web2py\applications\app\controllers\default.py

def index():
    """ Starts vue.js session
    
    The uuid is injected into the html <body> tag as
    the id.  For example: <body id="14e4de39-dc9e-467f-a28e-9c78bd485bc1">
    
    vue.js then uses status_load() to retrieve the session details.
    """
    uuid = session_new()
    return dict(UUID=uuid)

def status_load():
    uuid, error = IS_MATCH('[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\Z')(request.vars['uuid'])
    if error:
        raise HTTP(403, "Not authorized")
    query = (db.vue_session.uuid==uuid)
    session = db(query).select(orderby=~db.vue_session.expiry_datetime).first()
    if not session:
        raise HTTP(403, "Not authorized")
    return response.json(session)
    

====\web2py\applications\app\views\index.html
## The COMPILED VUE.JS FILE GOES HERE!!!


====\vue\index.html
<!DOCTYPE html>
<html>
  <head>
  </head>  
  <body id="{{=UUID}}">
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

====\vue\src\App.vue
<template>
  <div id="app" class="OuterWrapper">
    <div class="PageContainer">
        <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  components: {
  },
  data () {
    return {
    }
  },
  computed: {
  },
  methods: {
  },
  mounted: function () {
    // The uuid is injected into the parentElement by web2py
    // The store will then use the uuid to get the session from web2py
    // and may redirect to the restore_point
    this.$store.dispatch('NEW_UUID', { uuid: this.$el.parentElement.id })
  }
}
</script>

====\vue\src\store\index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import router from '../router'
Vue.use(Vuex)
var axiosi = axios.create({
  baseURL: '/myapp/default/',
  timeout: 5000
})
const store = new Vuex.Store({
  state: {
    // put your session variables here
  },
  actions: {
    NEW_UUID: function ({ commit, dispatch, state }, { uuid }) {
      // At the start of each session web2py gives us a uuid
      // We then go back to web2py and retrieve the session state
      commit('SET_UUID', { uuid: uuid })
      var data = {}
      data.uuid = uuid
      axiosi.post('status_load', data).then((response) => {
        commit('UPDATE_STATUS', { newState: response.data })
      }, (err) => {
        console.log(err)
        router.push({ name: 'error', params: { errorMessage: err.response.data } })
      })
    }


Val K

unread,
Aug 15, 2017, 7:40:57 PM8/15/17
to web2py-users


Considering the number of views, this issue is quite exciting.

Here is my experience. I use RapydML and  RapydScript to generate  Vue-components.

I wrote brute-force parser + made some hacks of RapydML-compiler so, as exhaust I receive single js-file with embeded template as html-string.

If anyone is interested, I can describe in more detail. In gVim it looks like this:




Massimo Di Pierro

unread,
Aug 15, 2017, 11:00:36 PM8/15/17
to web2py-users
I want to know more.

Carlos Kitu

unread,
Aug 16, 2017, 3:03:20 AM8/16/17
to web2py-users
I agree with you, @limedrop, for a fully "reactive"(let's call it that way) application I would also go your way. The use case I described only makes sense if you only need a small part of your application truly reactive.
Best regards.

Carlos Kitu

unread,
Aug 16, 2017, 3:14:54 AM8/16/17
to web2py-users
@valk: wow, that looks great. One of the most annoying things of working with vue.js was the need to write html.

After getting used to the helpful web2py's html helpers, writing pure html feels really verbose. With the code you showed, the view seems somewhat similar to working with html helpers, and also looks great to write the controller in python to have it translated to javascript, if you are used to python.
Thank you for sharing it.

Val K

unread,
Aug 16, 2017, 3:29:30 PM8/16/17
to web2py-users
@Massimo and @All concerned  
Uploaded to github with short manual and examples.
Discussion is welcome! 

António Ramos

unread,
Aug 16, 2017, 5:23:41 PM8/16/17
to web...@googlegroups.com
The first video tut about this deserves a beer...

Sem vírus. www.avast.com

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

António Ramos

unread,
Aug 17, 2017, 5:48:38 AM8/17/17
to web...@googlegroups.com

Massimo Di Pierro

unread,
Aug 23, 2017, 11:56:16 AM8/23/17
to web2py-users
This is fantastic!

Andrew Rogers

unread,
Feb 19, 2020, 11:15:11 AM2/19/20
to web...@googlegroups.com
I've been using Vue for just 30 mins and web2py for not much longer. I just wanted to get something really, really simple working. All i did was added this to index.html. I am sure this is bad practice - just a first step to trying to understand how things fit together. Thanks to Mirek's tip below i found how to change the Parameters correctly.
{{extend 'layout.html'}}

{{block header}}
<center style="background-color: #999; color:white; padding:30px">
    <h1>Login Screen</h1>
    <p>
        /{{=request.application}}/{{=request.controller}}/{{=request.function}}
    </p>
</center>

<div id="app">
    ${message}
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script>
    Vue.mixin({ delimiters: ['${', '}'] ,
                unsafeDelimiters: ['!{', '}'],
                silent: false
});

    // Configure Vuew
    new Vue({
        el: '#app',
        data: {
            'message': 'Hello World'
        }
    });
</script>

{{end}}

Geordanis Baño Vega

unread,
Feb 19, 2020, 11:18:53 AM2/19/20
to web...@googlegroups.com
API with web2py and SPA|PWA with Vue, could be an option. Regards

El mié., 19 feb. 2020 a las 11:16, Andrew Rogers (<roge...@gmail.com>) escribió:
I've been using Vue for just 30 mins and web2py for not much longer. I just wanted to get something really, really simple working. All i did was added this to index.html. I am sure this is bad practice - just a first step to trying to understand how things fit together. Thanks to Mirek's tip below i found how to change the Parameters correctly.
{{extend 'layout.html'}}

{{block header}}
<center style="background-color: #999; color:white; padding:30px">
    <h1>Login Screen</h1>
    <p>
        /{{=request.application}}/{{=request.controller}}/{{=request.function}}
    </p>
</center>

<div id="app">
    ${message}
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script>
    Vue.mixin({ delimiters: ['${', '}'] ,
                unsafeDelimiters: ['!{', '}'],
                silent: false,
                mixin: async = true
});

    // Configure Vuew
    new Vue({
        el: '#app',
        data: {
            'message': 'Hello World'
        }
    });
</script>

{{end}}




On Wednesday, 9 August 2017 07:24:12 UTC+6:30, 黄祥 wrote:
is there any simple web2py app with js framework (whatever) that have a CRUD or GRID example?
want to learn to combine it, but confuse, what is web2py job (define models, provide restful api, any others ?), what is js framework job (client side response) ? how about the form handling (web2py or js job?)
some of dev in here talk about vuejs, so i just look at it and learn from the example
https://vuejs.org/v2/examples/grid-component.html

but again, don't know how to connect it with web2py, any hints or example maybe.

thanks and best regards,
stifan

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/620507a2-0ce9-4fbc-ab65-3a4c68162dcc%40googlegroups.com.

Roberto Perdomo

unread,
Feb 19, 2020, 11:44:05 AM2/19/20
to web...@googlegroups.com
I made an app some time ago with Web2py/Vue is not being maintained
anymore, but maybe can help you.

https://github.com/robertop23/web2py_vuejs_vuetify
> To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/CAA4GC_vqDSEF245jh6DHNx-neGUqD%3DWu51yZOd56NVsT_atOyA%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages