w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Using Django along with Flask
If I were you I would take the Django templates from the designer and convert them to Jinja2, then build the application 100% in Flask. But since you asked... is this doable? or does this sound a crazy idea? Yes to both :) Can you kindly give some guidance? Here is a simple way: You write the two applications, one in Flask and one in Django. Let's assume you solve all the problems you will have when trying to share database or other resources and now you have the two applications running, each with its own web server and each listening for requests on a different port. You now put a proxy web server as your front web server to the outside world and proxy the requests that come from clients to one or the other application depending on the URL. You can make all the URLs for th

Categories : Django

How to structure a Flask app like in Django?
I usually put the initializations in __init__.py under the main project folder. __init__.py app = Flask(__name__) db = SQLAlchemy(app) import myproject.views import myproject.models models.py from myproject import app from myproject import db class User(db.Model): runserver.py (one level up) from myproject import app app.run(debug=True)

Categories : Python

Alembic Django Flask migrate database
You can use include_object from the environment context. The function can return True or False, indicating if the given table/object should be considered in the autogenerate sweep See here for more details: Alembic API

Categories : Django

Django-like date based archive with Flask and SqlAlchemy
The use of extract to filter by date components seems odd to me. I would instead create an auxiliary function that returns a range of dates from your year, month and day arguments: def get_date_range(year=None, month=None, day=None): from_date = None to_date = None if year and month and day: from_date = datetime(year, month, day) to_date = from_date elif year and month: from_date = datetime(year, month, 1) month += 1 if month > 12: month = 1 year += 1 to_date = datetime(year, month, 1) elif year: from_date = datetime(year, 1, 1) to_date = datetime(year + 1, 1, 1) return from_date, to_date And then the query function becomes much simpler: def live_post_filter(year=None, mon

Categories : SQL

Output Multi-line strings with Python Flask or other framework
Both Bottle and Flask can handle multi-line strings just fine. Your issue is that your data is being interpreted as text/html by default and in HTML any combination of whitespace is collapsed into a single space when displayed. In order to ensure that your data comes back exactly as you sent it you'll want to set the Content-Type header to text/plain. In Flask: # If you want *all* your responses to be text/plain # then this is what you want @app.after_request def treat_as_plain_text(response): response.headers["content-type"] = "text/plain" return response # If you want only *this* route to respond # with Content-Type=text/plain @app.route("/plain-text") def a_plain_text_route(): response = make_response(getKickstartFile()) response.headers["content-type"] = "text/plai

Categories : Python

Pass a variable to a Flask WTForm
See my another ansver: http://stackoverflow.com/a/17638018/880326. So it look like: form = transactionsForm(request.form, loan_id='default')

Categories : Python

Flask: URLs w/ Variable parameters
There are two ways to do this: Simply use the path route converter: @app.route("/mainsite/<path:varargs>") def api(varargs=None): # for mainsite/key1/key2/key3/keyn # `varargs` is a string contain the above varargs = varargs.split("/") # And now it is a list of strings Register your own custom route converter (see Werkzeug's documentation for the full details): from werkzeug.routing import BaseConverter, ValidationError class PathVarArgsConverter(BaseConverter): """Convert the remaining path segments to a list""" def __init__(self, url_map): super(PathVarArgsConverter, self).__init__(url_map) self.regex = "(?:.*)" def to_python(self, value): return value.split(u"/") def to_url(self, value): return u"/".join(valu

Categories : Python

Profiling Django views line-by-line
django-debug-toolbar which provides a bunch of debug information, including a profiler. django-devserver which is a drop-in replacement for django's runserver and has support for line_profiler Just have to add the module since it's not enabled by default DEVSERVER_MODULES = ( 'devserver.modules.sql.SQLRealTimeModule', 'devserver.modules.sql.SQLSummaryModule', 'devserver.modules.profile.ProfileSummaryModule', # Modules not enabled by default 'devserver.modules.ajax.AjaxDumpModule', 'devserver.modules.profile.MemoryUseModule', 'devserver.modules.cache.CacheSummaryModule', 'devserver.modules.profile.LineProfilerModule', )

Categories : Python

Django: Is there a way to display a variable in a Django template like foo.inspect in Rails?
There is a similar thread that has a number of good suggestions. If {% debug %} is unappealing, then it might be easier to inspect the variables in the view prior to the template rendering the page with the variables in question.

Categories : Django

Efficient session variable server-side caching with Python+Flask
Your instinct is correct, it's probably not the way to do it. Session data should only be ephemeral information that is not too troublesome to lose and recreate. For example, the user will just have to login again to restore it. Configuration data or anything else that's necessary on the server and that must survive a logout is not part of the session and should be stored in a DB. Now, if you really need to easily keep this information client-side and it's not too much of a problem if it's lost, then use a session cookie for logged in/out state and a permanent cookie with a long lifespan for the rest of the configuration information. If the information it too much size-wise, then the only option I can think of is to store the data other than the logged in/out state in a DB.

Categories : Python

Jinja2 and Flask: Pass variable into parent template without passing it into children
May I suggest you use the global variable 'g' in flask. This is by default available in the jinja templates. So you don't need to worry about passing it anywhere in the base template or children. Just make sure you set it first when you login g.username = user.name then in templates, just do this: You are logged in as {{ g.username }}

Categories : Python

Compare a text file line by line with a dynamic variable
If I understand the question correctly, this is what you need: File insert = new File("sample.txt"); BufferedReader br = new BufferedReader(new FileReader(insert)); String strLine; Boolean hasLine = false; while ((strLine = br.readLine()) != null) { if(strLine.equals(field)) { hasLine = true; break; } } br.close(); if (!hasLine) { FileWriter fw = new FileWriter(insert, true); BufferedWriter bw = new BufferedWriter(fw); bw.append(field + " "); // assumes field does not already have a newline bw.flush(); bw.close(); } Notice the break;. This will discontinue the while loop, since you already have the answer to what you are looking for. Your original code was doing: for every line: Do I equal field? Yes: goto next line No: append f

Categories : Java

How to split a line but keep a variable in the line unsplit in python
If they are all begin with "http" you could split them using http as delimiter, otherwise you could do two steps: First extract the first url from the string by using the space or http as firstSplit=line4.split(' ', 1) firstString= firstSplit.pop(0) -> pop the first url secondSplit =firstSplit.join() -> join the rest secondSplit[-1].split('lemon#gloss') ->splits the remaining two

Categories : Python

Flask-Login & Flask-Principle authenticated user drops to flask_login.AnonymousUserMixin
You need to instantiate principle after login. This is a repeat question, see here Flask Login and Principal - current_user is Anonymous even though I'm logged in

Categories : Python

python virtualenv and flask installation. No module named flask
I hope you had installed virtualenv and if you have create the virtual environment (virtualenv), you have to use . . venv/bin/activate command to activate the enviroment in unix or OSx. Hope you will get information from this source http://flask.pocoo.org/docs/installation/#installation

Categories : Python

flask/bin/pip install flask==0.9 results in 'no such file or directory'
Are you using a virtualenv? If you are not, I highly recommend that you should. You can checkout: virtualenv Also, to make things a bit easier you can also use virtualenvwrapper: virtualenvwrapper. That being said if you have pip installed on your machine, your should only run 'pip install flask==0.9', etc. You do not need the flask/bin part of the cmd as the tutorial says. Hope this helps.

Categories : Python

Flask on Ubuntu is unable to find Flask.json
In version 0.9 json (but it is in 0.10) is not a module. You can use it like this: from flask import json json.dumps(..) json.JSONEncoder This is actually a backwards-compatibiliy bug in the flask-wtf. This is fixed in the latest version of flask-wtf See the git diff here: https://github.com/ajford/flask-wtf/commit/6dea39dd2f130571c0028f1de6e489260fa01d47#flask_wtf/recaptcha/widgets.py I suggest you both use the latest versions of both flask-wtf and flask itself.

Categories : Python

Using the same database abstraction in Flask and non-Flask program
Using Flask-SQLAlchemy models out of a web context is a matter of creating a Flask application and call app.test_request_context().push() The point here is what you will do with your "non web" library. If it's not a problem to have the whole Flask library installed when you need to use the library then there's no problem at all using it in that way. If you plan to make performance improvements in the library data accessing code, like using different sessions, concurrency and such, then you're modifying your initial code so it's a totally different scenario. In this case a pure-SQLAlchemy approach might be better but it really depends on the differences between the two patterns. Normally with models comes methods and using 2 different ORM patterns (Flask-SQLAlchemy wrapper models and p

Categories : Python

How can I read a variable line by line?
You need to use a herestring: read -a names <<< $myVar < $myVar is telling the shell to read from a file named by the contents of $myvar, that is, a file named var1 var one var_one var_one (1) (with literal newlines). Obviously that file doesn't exist, so you're getting the error. <<< $myVar tells the shell to read the contents of the variable itself as the input, not a file named by it. If a shell doesn't have the herestring, you'll have to echo it: echo "$myVar" | read -a names

Categories : Linux

Flask-frozen don’t work whereas flask is ok
Enable testing while freezing your application. It should produce more information about error. @command def build(): """ Builds this site. """ print("Building website...") app.debug = False app.testing = True asset_manager.config['ASSETS_DEBUG'] = False freezer.freeze() local("cp ./static/*.ico ./build/") local("cp ./static/*.txt ./build/") local("cp ./static/*.xml ./build/") print("Done.") Frozen-flask uses app.test_client() look at it's docs.

Categories : Python

Why Isn't 'Puts' Used in Applications?
puts method is essentially a "print to_s", which receives an object (number, string, etc) tries to convert it to string and then print it. Since most of the ruby apps are web it is rare to see it being used on these ones, where we can just use a variable in a html/erb template, however it is usually used in ruby scripts, rake tasks and other kind of stuff that relies just on terminal.

Categories : Ruby On Rails

C puts() without newline
puts() adds the newline character by the library specification. You can use printf instead, where you can control what gets printed with a format string: printf("%s", input);

Categories : C

Django run models.py from command line
run this from project root dir :- it works :D import os import sys from django.conf import settings os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)) + '/../') from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Meta: app_label = #app_name your second class if __name__ == "__main__": print Poll.objects.all() import datetime p = Poll(question="What's up?", pub_date=datetime.datetime.now()) p.save() print p.id print p.question print p.pub_date p.pub_date = datetime.datetime(2007, 4, 1, 0, 0) p.save()

Categories : Django

puts statements in production
First, don't use puts sprinkled everywhere. Bottleneck your "debug" output in a single method. That way you can very easily control the output, redirect it, massage it, etc. For instance, these might be the growth from a simple logging method to something more sophisticated: def debug_output(s) STDERR.puts s end --- DEBUG_OUTPUT_MINIMUM_LEVEL = 3 def debug_output(s, level=DEBUG_OUTPUT_MINIMUM_LEVEL) STDERR.puts s if level >= DEBUG_OUTPUT_MINIMUM_LEVEL end --- require 'logger' LOGGER_OUTPUT_FILE = '/path/to/log/output' def debug_output(s) @logger ||= Logger.new(LOGGER_OUTPUT_FILE) @logger << s end There are better tools available to you than puts though. Learn to use the debugger, or PRY in debugging mode and/or use Ruby's built-in Logger or Syslog so you can contro

Categories : Ruby On Rails

Cannot get puts to display read()
You should open target for reading as such: target = File.open(filename, 'r') According to the docs, read takes an integer argument for the number of bytes to read. Instead of this I suggest using an iterative approach and printing the lines one by one. You also will not have to open the file before, but I thought I would show you the 'r' argument in open anyways. This is what I would do: IO.foreach(filename) do |line| puts line end This method closes the file after the block is done so no need to explicitly call close. Before this read though, make sure to close the file after you have written to it.

Categories : Ruby

Output value of puts in Ruby
You're confusing printing with returning a value. puts returns nil, and each_slice does not return the result of the block anyway. What you want is this: def pair_array pair.each_slice(2).map {|arr| arr.join ' & '} end

Categories : Ruby On Rails

Django getting encoding error only on command line
Ah, don't use str(result). instead, do: result.encode('utf-8') When you call str(result), python will use the default system encoding (usually ascii) to try and encode the bytes in result. This will break if the ordinal not in range(128). Rather than using the ascii codec, just .encode() and tell python which codec to use. Check out the Python Unicode HowTo for more information. You might also want to check out this related question or this excellent presentation on the subject.

Categories : Python

ruby puts - how to avoid getting nil for each map iteration
What you do with map is return the result in another array.. and puts returns nil.. and irb prints the return value. So this is expected behavior. You can print out the methods with puts r.methods or in irb just r.methods irb(main):002:0> (1..2).methods => [:==, :===, :eql?, :hash, :each, :step, :begin, :end, :first, :last, :min, :max, :to_s, :inspect, :exclude_end?, :member?, :include?, :cover?, :to_a, :entries, :sort, :sort_by, :grep, :count, :find, :detect, :find_index, :find_all, :select, :reject, :collect, :map, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :all?, :any?, :one?, :none?, :minmax, :min_by, :max_by, :minmax_by, :each_with_index, :reverse_each, :each_entry, :each_slice, :each_cons, :each_with_object, :zip, :take, :take_while, :drop, :drop_wh

Categories : Ruby

In Ruby, why is my base class only being puts once?
The problem in your code is that: puts "This animal can:" is run when the Animal class gets defined. It seems like you want this in the initializer: class Animal def initialize(name) puts "This animal can:" end end You'll then need to call super in the other initializers for the result you're expecting.

Categories : Ruby

Node/less: util.puts: Use console.log instead
The -pre on the node version got me suspicious. Turns out, it's a bad build. I grabbed a stable release off the downloads page and that seems to have fixed the issue.

Categories : Node Js

Why doesn't $stdout puts work?
One possible problem is you are not closing your file stream. It's important to do so because the File buffer might not have been flushed to the file itself. Because your code is generating an error with the zero-divison, Ruby might not have closed the file correctly too. That said, your code could be written much more cleanly and Ruby-like, without subverting how puts can be used to write to a file: File.open("/tmp/record", "w") do |record| record.puts "This is a record" end That will automatically close the file output when the block exits. Perhaps you're trying to capture the output of the self-induced zero-division exception you're generating using z = 10/0? You can do that by rescuing the exception; You can't get Ruby to continue running without that: File.open("./record",

Categories : Ruby

Running the flask/python code in linux? Basic flask code
It says App module not defined You misspelled package name: you have apps in your directory tree and you try to import app Where should I put the run.py file? Anywhere you want as long app is in PYTHONPATH. Or you can put it inside microblog directory. he is importing flask which is normal. then assigning app = (name). why is that? # Create reference to flask WSGI application object app = Flask(__name__) Why? Because you need application to run. See official docs: Flask object Then why is he importing views from apps? from app import views means: From package named app import module named views Naming convention could be probably different but if you don't see the difference you should probably spend more learning python basics before starting with more sophist

Categories : Python

Add "django-admin.py" path to command line on Windows 7
Try following command. set path=%path%;c:python27scripts PATH is set only for the cmd.exe in which you run the above command. UPDATE To permanently set PATH: Right click My computer in the desktop. Click Advanced System Settings on the left. Click Environmental Variable. Add or Update PATH variable: If it does not exist, create one, and set value as C:python27scripts If it exist, append ;C:Python27scripts to existing value. Restart cmd.exe. (PATH will not change for already launched cmd.exe)

Categories : Python

AJAX get request puts each letter into array
Try this: $.getJSON('../poll/index.php?data=vehicles', function(data) { for (var i = 0; i < data.length; i++) { vehicles.push(data[i]); } console.log(vehicles); });

Categories : Javascript

Cleanup function which puts age in age group bucket - possible?
As a base you can use the following code for your increments: private function calculateAgeGroup($age) { if (!$age) return null; for ($i=25; $i<=60; $i+=5) { if ($age <= $i) return ($i-4 > 25 ? $i-4 : 0) . '-' . $i; } return '61-'; }

Categories : PHP

FF puts credentials to url of XHR request. Is it a security risk?
Yes There is a security risk to send the user name password with url, Even if you are using SSL. Most of the router and get-way ,firwall/server logs the request url, so if User Name and Password appended with url as querystring it can be logged. But if it is possible to send the credential as post data, and using SSL the data are encrypted so it is not visible during transmission.

Categories : Ajax

Make API Request, puts response in RAILS 4.0.0
It depends entirely on how your application is going to be set up but here's a basic example: Say you have a Survey model: class Survey < ActiveRecord::Base attr_accessible :survey_id end You can place your call for a list of surveys (I'm assuming that's what your code does) in the SurveysController: class SurveysController < ApplicationController def index @surveys = Survey.all end def show @survey = Survey.find(params[:id]) end def pull_surveys call= "/api/v2/surveys/" auth = {:username => "test", :password => "password"} url = HTTParty.get("https://surveys.com#{call}", :basic_auth => auth, :headers => { 'ContentType' => 'application/json' } ) response = JSON.parse(url.body) survey_ids = response["surveys"].map { |s| s["id"] }

Categories : Ruby On Rails

Why does capistrano puts my Rails app in Releases folder?
This is done for couple of reasons app doesn't go down during deploy (as some files would be overwritten while app is still running in the same dir) so you can easily and quickly rollback in case of fuckup on deploy Also, current release should be symlinked to /var/www/-myappname-/current and that's there your server should point to.

Categories : Ruby On Rails

How to I temporarily override print and puts from a class?
Well, I think I fixed the problem, but I'm not sure why it works. I'm guessing that the blocks are in both the scope where it was called from, as well as in the scope they were defined in, but with higher priority on the former. That would mean that I can't use self and expect it to point to the shell. Instead I did this: shell = self Kernel.module_exec { define_method(:print) { |text = ""| shell.send(:print_override, master_print, text) } define_method(:puts) { |text = ""| shell.send(:puts_override, master_puts, text) } define_method(:puts_padded) { |text = ""| shell.send(:puts_override, master_puts, "") shell.send(:puts_override, master_puts, text) shell.send(:puts_override, master_puts, "") } } Which works perfectly but (if I'm right) would break as s

Categories : Ruby

The New line ( ) wasn't selected in Django admin changelist page
New lines are ignored by browsers in HTML. If you want to show them in different lines I think you should join them with <br> instead of and use allow_tags. class ArticleAdmin(admin.ModelAdmin): list_filter = ["category",] list_display = ('category','article_type', 'get_domains') filter_horizontal = ("domain",) def get_domains(self, obj): x ="<br>".join([str(s.name) for s in obj.domain.all()]) print x # printing fine return x get_domains.allow_tags = True Hope this helps!

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.