How to create an atom template for python - python

I have the following class i am tired of writing it out every time. I need an atom template. For example if i were to type luigt and press enter the code would appear.
class TaskName(luigi.Task):
"""GENERAL TASK."""
def requires(self):
"""test."""
return None
def run(self):
"""test."""
pass
def output(self):
"""test."""
return luigi.LocalTarget('default')

Have a look to the snippets here.
You can define code snippets in there and a shortcut. I think this is exactly what you are looking for.
Extraction from the snippet page:
There is a text file in your ~/.atom directory called snippets.cson that contains all your custom snippets that are loaded when you launch Atom. You can also easily open up that file by selecting the Edit > Snippets menu.
Snippet Format
So let's look at how to write a snippet. The basic snippet format looks like this:
'.source.js':
'console.log':
'prefix': 'log'
'body': 'console.log(${1:"crash"});$2'
For more details, please have a look at the snippet page provided.

Related

How to create and or edit a page with pyWikiBot

The MediaWiki API has an edit function which is available within pywikibot.
According to https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.site.html
the function is called with a page parameter:
editpage(page, summary=None, minor=True, notminor=False, bot=True, recreate=True, createonly=False, nocreate=False, watch=None, **kwargs)[source]ΒΆ
A page needs a source to be constructed. I could not find an example for this.
E.g.: How to add something to edit summary when using Pywikibot?
has just one line as the accepted answer and does not use site or page. I am confused.
What is the proper approach do create and or edit a page with pyWikiBot directly using python code? (not script ...)
https://github.com/wikimedia/pywikibot/blob/master/pywikibot/page/init.py#L2328
has the constructor:
"""Page: A MediaWiki page."""
#deprecated_args(defaultNamespace='ns', insite=None)
def __init__(self, source, title='', ns=0):
"""Instantiate a Page object."""
if isinstance(source, pywikibot.site.BaseSite):
if not title:
raise ValueError('Title must be specified and not empty '
'if source is a Site.')
super(Page, self).__init__(source, title, ns)
Which is unfortunately not properly documented and part of the 6000 line init.py file having all the classes.
When trying
newPage=Page(site,pageTitle)
newPage.text=pageContent
I get
AttributeError: APISite instance has no attribute 'edit'
site.edit(newPage,'summary')
The following code works:
from pywikibot.page import Page
newPage=Page(site,pageTitle)
newPage.text=pageContent
newPage.save("summary")
see also https://www.mediawiki.org/wiki/Manual:Pywikibot/Create_your_own_script
It's just unfortunate that the documentation at https://pypi.org/project/pywikibot/ is not using standard python documentation tools.

Python Flask: How do converters work? (dynamic routing)

I am trying to get Flask converters up and running as shown in the manual: http://flask.pocoo.org/docs/0.12/api/#url-route-registrations
Right now, I have currently four pages defined like so:
#app.route('/page1')
def page1():
return render_template("page1.html")
#app.route('/page2')
def page2():
return render_template("page2.html")
#app.route('/page3')
def page3():
return render_template("page3.html")
#app.route('/page4')
def page4():
return render_template("page4.html")
I could not find yet a way to automate this repetitive notation and would be grateful for hints.
You can create dynamic routes by using converters.
You'd then define your route like this:
#app.route("/<page>")
def pages(page):
return render_template(page + ".html")
Which will accept all of your paths.
You can also be more specific in what you allow in the dynamic paths, such as:
#app.route("/post/<int:post_id>")
def show_post(post_id):
pass
Which would accept /post/1, /post/2, /post/100 but not /post/test.

Pyramid TranslationString not working on json renderer

In a test I am doing in a pyramid application, I am trying to send a translatable text via JSON, but the translation is not working. At the beginning of the file I am importing the translation string function:
from pyramid.i18n import TranslationString as _
Then consider the following code:
#view_config(route_name='transtest', renderer='json')
def transtest_view(request):
return { 'myvar': _('temp-test', default='Temporary test', domain='myapp') }
But what I get is:
{"myvar": "temp-test"}
Note that if I change the renderer to a test template I did as follows:
#view_config(route_name='transtest', renderer='../templates/transtest.pt')
...
then the text gets translated correctly (note that I already initialized the catalogs, updated them, compiled them, etc.)
This made me think that the TranslationString class does not work right in a 'json' renderer? If so, how can I make to send a translatable string via JSON?
Thanks in advance
You need to explicitly translate your message string, using get_localizer() and Localizer.translate():
from pyramid.i18n import get_localizer
#view_config(route_name='transtest', renderer='json')
def transtest_view(request):
message = _('temp-test', default='Temporary test', domain='myapp')
return {'myvar': get_localizer(request).translate(message)}
Normally, templates take care of these steps for you, but for JSON you'll need to do so yourself.
You probably want to define a TranslationStringFactory for your project, and reuse that to produce your message strings. Add the following to your project:
from pyramid.i18n import TranslationStringFactory
myapp_domain = TranslationStringFactory(domain='myapp')
then use:
from my.project import myapp_domain as _
# ....
message = _('temp-test', default='Temporary test')

redirect while passing arguments

In flask, I can do this:
render_template("foo.html", messages={'main':'hello'})
And if foo.html contains {{ messages['main'] }}, the page will show hello. But what if there's a route that leads to foo:
#app.route("/foo")
def do_foo():
# do some logic here
return render_template("foo.html")
In this case, the only way to get to foo.html, if I want that logic to happen anyway, is through a redirect:
#app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
return redirect("/foo", messages={"main":"Condition failed on page baz"})
# above produces TypeError: redirect() got an unexpected keyword argument 'messages'
So, how can I get that messages variable to be passed to the foo route, so that I don't have to just rewrite the same logic code that that route computes before loading it up?
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
#app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
#app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
#app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
You can however maintain your code and simply pass the variables in it separated by a comma: if you're passing arguments, you should rather use render_template:
#app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
return render_template("/foo", messages={"main":"Condition failed on page baz"})

How to put css files to head by means UIModule in the tornado?

I want to add set of css files to head. For instance,
python file:
modules.py
class SomeModule(tornado.web.UIModule):
def css_files(self):
return [self.handler.static_url('css/modules/some-module.css'),]
def render(self, some_data=None):
result = ''
if some_data is not None:
"""to do something with data"""
return result
server.py
app = Application(
...
ui_module=modules
...
)
template file:
...
{% module SomeModule(some_data=put_data_here) %}
As the result, I see only data that were returned from render. But css files weren't set between head tags.
What's the result of the template file depends on how you generate the template file. As far as I can see, you didn't include the code for that in your question.
If you want to use css_files() or similar, you need to use self.render_string() in order to give Tornado a chance to insert the CSS tags in the proper places.
For an example of how to use tornado.web.UIModule, see this Slideshare presentation

Categories

Resources