-
Notifications
You must be signed in to change notification settings - Fork 0
/
introducao-ao-web2py.html
374 lines (324 loc) · 18.4 KB
/
introducao-ao-web2py.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
<!DOCTYPE html>
<html lang="pt" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml">
<head>
<title>Introdução ao web2py - import None</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="http://cassiobotaro.github.io/introducao-ao-web2py.html">
<meta name="author" content="Cássio Botaro" />
<meta name="keywords" content="web2py,iniciantes" />
<meta name="description" content="Uma breve introdução prática ao framework web2py e uma lista de recursos interessantes." />
<meta property="og:site_name" content="import None" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="Introdução ao web2py"/>
<meta property="og:url" content="http://cassiobotaro.github.io/introducao-ao-web2py.html"/>
<meta property="og:description" content="Uma breve introdução prática ao framework web2py e uma lista de recursos interessantes."/>
<meta property="article:published_time" content="2015-05-04" />
<meta property="article:section" content="web2py" />
<meta property="article:tag" content="web2py" />
<meta property="article:tag" content="iniciantes" />
<meta property="article:author" content="Cássio Botaro" />
<!-- Bootstrap -->
<link rel="stylesheet" href="http://cassiobotaro.github.io/theme/css/bootstrap.united.min.css" type="text/css"/>
<link href="http://cassiobotaro.github.io/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="http://cassiobotaro.github.io/theme/css/pygments/monokai.css" rel="stylesheet">
<link rel="stylesheet" href="http://cassiobotaro.github.io/theme/css/style.css" type="text/css"/>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="http://cassiobotaro.github.io/" class="navbar-brand">
import None </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li >
<a href="http://cassiobotaro.github.io/category/linux.html">Linux</a>
</li>
<li >
<a href="http://cassiobotaro.github.io/category/python.html">Python</a>
</li>
<li >
<a href="http://cassiobotaro.github.io/category/python3.html">Python3</a>
</li>
<li >
<a href="http://cassiobotaro.github.io/category/sublime.html">Sublime</a>
</li>
<li class="active">
<a href="http://cassiobotaro.github.io/category/web2py.html">Web2py</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://cassiobotaro.github.io/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<section id="content">
<article>
<header class="page-header">
<h1>
<a href="http://cassiobotaro.github.io/introducao-ao-web2py.html"
rel="bookmark"
title="Permalink to Introdução ao web2py">
Introdução ao web2py
</a>
</h1>
</header>
<div class="entry-content">
<div class="panel">
<div class="panel-body">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2015-05-04T00:00:00-03:00"> Seg 04 maio 2015</time>
</span>
<span class="label label-default">Tags</span>
<a href="http://cassiobotaro.github.io/tag/web2py.html">web2py</a>
/
<a href="http://cassiobotaro.github.io/tag/iniciantes.html">iniciantes</a>
</footer><!-- /.post-info --> </div>
</div>
<p><img alt="Web2py Logo" src="../images/web2py_logo.png" /></p>
<h2>Sobre o web2py</h2>
<p>Framework full-stack(ou seja assim como python vem com baterias incluídas), para desenvolvimento rápido, seguro, portável e orientado a banco de dados(o que não o limita).</p>
<p>O download pode ser feito através da página <a href="http://www.web2py.com/download">http://www.web2py.com/</a> e quando este artigo foi escrito estava em sua versão 2.10.X.</p>
<p>Embora possua versões para Windows e MAC eu recomendo sempre baixar a versão de código fonte.</p>
<h2>Hello Web2py(Talk is cheap. Show me the code)</h2>
<p>Iniciaremos criando uma aplicação mínima no web2py(sem utilizar sua interface ou um scaffolding).</p>
<p>Navegue até o diretório applications do web2py, crie um diretório com o nome da sua aplicação(Eu chamerei o exemplo de hello).</p>
<p>Dentro deste diretório inclua um diretório chamado controllers.</p>
<p>Em seguida crie um arquivo chamado default.py no diretório controllers e digite o seguinte código.</p>
<div class="highlight"><pre><span class="k">def</span> <span class="nf">index</span><span class="p">():</span>
<span class="k">return</span> <span class="s">'Hello World'</span>
</pre></div>
<p>Vá no diretório raiz do web2py, rode o arquivo web2py.py e pronto!
Para acessar sua aplicação utilize a seguinte url: http://127.0.0.1:8000/hello</p>
<p>Duas observações devem ser feitas neste ponto, caso navegue no diretório da sua aplicação vai notar que outros diretórios foram criados(nao se reocupe com eles por enquanto). Outra coisa é o nome do arquivo python(default) e a função(index). Isto é um padrão e pode ser modificado utilizando um arquivo de rotas.</p>
<p>Todo o processo acima pode ser resumido da seguinte maneira(à partir da raiz do diretório web2py):</p>
<div class="highlight"><pre>mkdir applications/hello <span class="c"># criação da aplicação</span>
mkdir applications/hello/controllers <span class="c"># criação da pasta controllers</span>
<span class="nb">echo</span> <span class="s2">"def index():"</span> > applications/hello/controllers/default.py
<span class="nb">echo</span> <span class="s2">" return 'Hello World'"</span> >> applications/hello/controllers/default.py
</pre></div>
<p><img alt="Web2py Word Cloud" src="../images/tag-cloud-web2py.png" /></p>
<h2>Hello Author</h2>
<p>Vamos tornar nosso primeiro aplicativo web mais interessante, vamos faze-lo passar a exibir um nome recebido como argumento em nossa url.</p>
<p>Abra novamente o controlador default.py e agora adicione o seguinte código:</p>
<div class="highlight"><pre><span class="k">def</span> <span class="nf">index</span><span class="p">():</span>
<span class="n">nome</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">args</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">return</span> <span class="p">{</span><span class="s">'nome'</span><span class="p">:</span> <span class="n">nome</span><span class="p">}</span>
</pre></div>
<p>O código agora foi alterado, para incialmente receber uma variável chamada nome que contém o valor do argumento 0.</p>
<p>Argumento 0, wtf? </p>
<p>Uma url pode ser decomposta assim no web2py:
http://host/application/controller/action/args1/args2...?var1=valor&var2=valor</p>
<div class="highlight"><pre>- host - Domínio ou subdominio da sua aplicação(Pode ser www.algo.com ou localmente localhost:8000 sendo 8000 porta padrão do servidor web2py)
- application - nome da sua aplicação
- controller - nome do controlador
- action - nome da função presente no controlador
- args - argumentos(como parâmetros)
- vars - são como variáveis e sempre tem um nome e um valor
</pre></div>
<p>O retorno que anteriormente era um string, agora é um dicionário, este dicionário são as variáveis que estarão disponíveis na template para o contexto desta ação.</p>
<p>Agora crie um diretório default na pasta views e em seguida adicione um arquivo chamado index.html dentro deste diretório.</p>
<p>Neste arquivo adicione o seguinte conteúdo:</p>
<div class="highlight"><pre><span class="cp"><!DOCTYPE html></span>
<span class="nt"><html</span> <span class="na">lang=</span><span class="s">"pt-br"</span><span class="nt">></span>
<span class="nt"><head></span>
<span class="nt"><meta</span> <span class="na">charset=</span><span class="s">"UTF-8"</span><span class="nt">></span>
<span class="nt"><title></span>Hello<span class="nt"></title></span>
<span class="nt"></head></span>
<span class="nt"><body></span>
<span class="nt"><h1></span>Hello {{=nome}}<span class="nt"></h1></span>
<span class="nt"></body></span>
<span class="nt"></html></span>
</pre></div>
<p>Repare que este arquivo é um arquivo html comum, porém na Tag H1 eu utilizo da linguagem de template do web2py para adicionar um recurso dinamicamente ao html.</p>
<p><code>{{}}</code> é a maneira da template do web2py reconhecer que aquele código será avaliado antes de retornar uma resposta ao cliente. O igual indica que uma expressão deve ser avaliada e o retorno será adicionado ao html, no caso do exemplo uma variável será adicionada.
Como pode ser visto a variável nome que foi definida para o ambiente desta action(default/index) está disponível em minha template.</p>
<p>Agora acesse http://localhost:8000/hello/default/index/cassio ou substitua cassio por algo que queira e veja o resultado.</p>
<h2>Considerações finais</h2>
<p>Este foi o primeiro post sobre web2py do meu blog, quis ser breve. Se ficou perdido em algum detalhe, não se preocupe, deixe um comentário que adorarei lhe ajudar.</p>
<p>E já adiantando, teremos continuação para este post, demonstrando diversos recursos do framework e também dscutindo sobre suas "mágicas".</p>
<p>Gostou? Compatilhe!</p>
<p>[ ]'s</p>
</div>
<!-- /.entry-content -->
<hr />
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
</div>
<!-- AddThis Button END -->
<hr/>
<section class="comments" id="comments">
<h2>Comments</h2>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'importnone'; // required: replace example with your forum shortname
var disqus_identifier = 'introducao-ao-web2py';
var disqus_url = 'http://cassiobotaro.github.io/introducao-ao-web2py.html';
var disqus_config = function () {
this.language = "pt";
};
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by
Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</section>
</article>
</section>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<div id="aboutme">
<p>
<img width="100%" class="img-thumbnail" src="http://www.gravatar.com/avatar/a19c2dcbc9fc6ae1c340528186320d9c?s=100"/>
</p>
<p>
<strong>About Cássio Botaro</strong><br/>
WebDeveloper at Diarios Associados. UHlzc2lvbmF0ZSB3ZWJkZXZlbG9wZXIuCg==
</p>
</div>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4>
<ul class="list-group" id="social">
<li class="list-group-item"><a href="https://github.com/cassiobotaro"><i class="fa fa-github-square fa-lg"></i> github</a></li>
<li class="list-group-item"><a href="http://twitter.com/cassiobotaro"><i class="fa fa-twitter-square fa-lg"></i> twitter</a></li>
<li class="list-group-item"><a href="https://plus.google.com/u/0/+C%C3%A1ssioBotaro"><i class="fa fa-google-plus-square fa-lg"></i> google-plus</a></li>
<li class="list-group-item"><a href="http://br.linkedin.com/pub/c%C3%A1ssio-botaro/b1/43/6a2"><i class="fa fa-linkedin-square fa-lg"></i> linkedin</a></li>
</ul>
</li>
<li class="list-group-item"><a href="http://cassiobotaro.github.io/"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group list-inline tagcloud" id="tags">
</ul>
</li>
<li class="list-group-item"><h4><i class="fa fa-github fa-lg"></i><span class="icon-label">GitHub Repos</span></h4>
<div id="gh_repos">
<p class="list-group-item">Status updating...</p>
</div>
<a href="https://github.com/cassiobotaro">@cassiobotaro</a> on GitHub
</li>
<li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4>
<ul class="list-group" id="links">
<li class="list-group-item">
<a href="http://getpelican.com/" target="_blank">
Pelican
</a>
</li>
<li class="list-group-item">
<a href="http://python.org/" target="_blank">
Python.org
</a>
</li>
<li class="list-group-item">
<a href="http://jinja.pocoo.org/" target="_blank">
Jinja2
</a>
</li>
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2015 Cássio Botaro
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="http://cassiobotaro.github.io/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://cassiobotaro.github.io/theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="http://cassiobotaro.github.io/theme/js/respond.min.js"></script>
<!-- GitHub JS -->
<script type="text/javascript">
$(document).ready(function () {
if (!window.jXHR) {
var jxhr = document.createElement('script');
jxhr.type = 'text/javascript';
jxhr.src = 'http://cassiobotaro.github.io/theme/js/jXHR.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(jxhr, s);
}
github.showRepos({
user: 'cassiobotaro',
count: 3,
skip_forks: true,
target: '#gh_repos'
});
});
</script>
<script src="http://cassiobotaro.github.io/theme/js/github.js" type="text/javascript"></script>
<!-- End GitHub JS Code -->
<!-- Disqus -->
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'importnone'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<!-- End Disqus Code -->
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-59964005-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- End Google Analytics Code -->
<script type="text/javascript">var addthis_config = {"data_track_addressbar": true};</script>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-54023148366c6bdd"></script>
</body>
</html>