Could not build url for endpoint '_uploads.uploaded_file' with values ['filename', 'setname'] when i use flask-reuploaded to upload the image - flask-wtforms

I get into trouble when I would like to store the image_url for updating the picture of my product. The flask extensions that I used are flask-reuploaded and flask-wtf. I have tried to search a lot but still cannot figure out a solution. Could you help me, please?
This is my app.py:
#app.route('/admin/add', methods=['GET', 'POST'])
def add():
form = AddProduct()
if form.validate_on_submit():
image_name = photos.save(form.image.data)
image_url = photos.url(image_name)
return '<h1>{}</h1>'.format(image_url)
return render_template('admin/add-product.html', admin=True, form=form)
I also include <form method="POST" action="{{ url_for('add') }}" enctype="multipart/form-data"> in my template but it doesn't help.
The error message is that werkzeug.routing.BuildError: Could not build url for endpoint '_uploads.uploaded_file' with values ['filename', 'setname']. Did you mean 'product' instead?
Thank you in advance, everyone.

I had the same issue and managed to fix it this way. I am sure someone who is way better at Python can give an explanation to what I did to fix it.
The problem is this blueprint route is not registered: _uploads.uploaded_file. I set this config item UPLOADS_AUTOSERVE=True
This allows the default route in flask_uploads.py to be used. I didn't bother with this, but it also looks like you could set the base_url in the UploadConfiguration. The class says
:param base_url: The URL (ending with a /) that files can be downloaded from. If this is None, Flask-Reuploaded will serve the files itself.
Also, I would add, you don't need to save the url. You can do upload_set.url(filename). Or upload_set.path(filename) if you wanted to modify it with a different module like PIL.

Related

SilverStripe 4.1 Email->addAttachment()?

I have a contact form that accepts a file input, I'd like to attach the file to the email that gets sent from the form.
Looking at the API reference isn't really helping, it states that the function expects a filepath with no clarification on anything beyond that.
The submit action will save a record of the into the database and this works correctly, something like:
$submission = MyDataObject::create();
$form->saveInto($submission);
$submission->write();
an Email object then gets created and sent. Both of these are functioning and working as expected.
Trying to attach the File I've tried:
$email->addAttachemnt($submission->MyFile()->Link());
which is the closest I can get to getting a filepath for the document. Dumping and pasting the resulting filepath being output by that call will download the form but that line throws an error and can't seem to locate the file.
I suspect that I'm misunderstanding what's supposed to be given to the function, clarification would be very much appreciated.
P.S. I don't currently have access to the code, I'm looking for some clarification on the function itself not an exact answer :).
In SilverStripe 4 the assets are abstracted away, so you can't guarantee that the file exists on your webserver. It generally will, but it could equally exist on a CDN somewhere for example.
When you handle files in SilverStripe 4 you should always use the contents of the file and whatever other metadata you have available, rather than relying on filesystem calls to load it.
This is how the silverstripe/userforms module attaches files to emails:
/** #var SilverStripe\Control\Email\Email $email */
$email->addAttachmentFromData(
$file->getString(), // stream of file contents
$file->getFilename(), // original filename
$file->getMimeType() // mime type
);
I would try $email->addAttachment($submission->MyFile()->Filename); If it doesn't work, you may need to prepend $_SERVER['DOCUMENT_ROOT'] to the filename.
$email->addAttachment($_SERVER['DOCUMENT_ROOT'] . $submission->MyFile()->Filename);

Smarty - url function with parameter

I am using smarty in my symfony3 application.
I would like to generate an url with parameters in smarty based on symfony routing-system:
Activate
This part creates a normal url like:
http://example.com/activation
What i would like create:
http://example.com/activation?key=param
Anyone knows how to create these params and pass them to the url?
Thanks and Greetings!
Try:
{{ url('activation', {'key':'param'}) }}

CQ5 SlingServlet and resourceTypes not working for specific resource paths

If I define a Sling Servlet as follows:
#SlingServlet(
label="TestResourceTypeServlet",
name = "com.company.project.servlets.TestResourceType",
extensions = {"bob"},
resourceTypes= {"cq:Page"},
methods= {"GET"},
metatype=true)
#Properties({
#Property(name = "service.description", value = "A test servlet"),
#Property(name = "service.vendor", value = "Company")
})
The servlet picks up any get request to every page with an extension of '.bob', which is fine but what I really want is to handle a request to a specific page type,
SO
I modify resourceTypes to read
resourceTypes= {"site-administration/components/page/page-distribution"},
the supplied value is the specific sling:resourceType (copied and pasted out of CRXDE Lite) of a page I am trying to access with the .bob extension, but I get a 404!!!
All the documentation I've read says the above should work, but it does not.
Out of desperation I've even tried "site-administration/components/page" which is the super type of the page I want.
I'm running a clean 5.6.1 instance with this servlet as part of an OSGi bundle.
Am I missing something obvious here, or if not is anyone aware of any hot fixes that could resolve this issue ?
Any help would be appreciated as I'm starting to go slightly mad in the head.
EDIT
Ok, so I've gotten a little further: If I access the page with:
[path-to-page]/page.bob.html
The servlet fires. But in this URL is bob not a selector? and if so why when the resource type is cq:Page does the configuration work with bob as an extension?
Very confused :-S
I'm obviously missing something very simple here.
The problem with pages is that the resourceType is stored on the jcr:content node below the cq:Page node. If you would call [path-to-page]/_jcr_content.bob it should work. Note: _jcr_content is an url save version of jcr:content.
Why your last example is actually working, I cannot tell.

Meteor how to save templates in mongo

I want to give my users the possibility to create document templates (contracts, emails, etc.)
The best option I figured out would be to store these document templates in mongo (maybe I'm wrong...)
I've been searching for a couple of hours now but I can't figure out how to render these document template with their data context.
Example:
Template stored in Mongo: "Dear {{firstname}}"
data context: {firstname: "Tom"}
On Tom's website, He should read: "Dear Tom"
How can I do this?
EDIT
After some researches, I discovered a package called spacebars-compiler that brings the option to compile to the client:
meteor add spacebars-compiler
I then tried something like this:
Template.doctypesList.rendered = ->
content = "<div>" + this.data.content + "</div>"
template = Spacebars.compile content
rendered = UI.dynamic(template,{name:"nicolas"})
UI.insert(rendered, $(this).closest(".widget-body"))
but it doesn't work.
the template gets compiled but then, I don't know how to interpret it with its data context and to send it back to the web page.
EDIT 2
I'm getting closer thanks to Tom.
This is what I did:
Template.doctypesList.rendered = ->
content = this.data.content
console.log content
templateName = "template_#{this.data._id}"
Template.__define__(templateName, () -> content)
rendered = UI.renderWithData(eval("Template.#{templateName}"),{name:"nicolas"})
UI.insert(rendered, $("#content_" + this.data._id).get(0))
This works excepted the fact that the name is not injected into the template. UI.renderWithData renders the template but without the data context...
The thing your are missing is the call to (undocumented!) Template.__define__ which requires the template name (pick something unique and clever) as the first argument and the render function which you get from your space bars compiler. When it is done you can use {{> UI.dynamic}} as #Slava suggested.
There is also another way to do it, by using UI.Component API, but I guess it's pretty unstable at the moment, so maybe I will skip this, at least for now.
Use UI.dynamic: https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/
It is fairly new and didn't make its way to docs for some reason.
There are few ways to achieve what you want, but I would do it like this:
You're probably already using underscore.js, if not Meteor has core package for it.
You could use underscore templates (http://underscorejs.org/#template) like this:
var templateString = 'Dear <%= firstname %>'
and later compile it using
_.template(templateString, {firstname: "Tom"})
to get Dear Tom.
Of course you can store templateString in MongoDB in the meantime.
You can set delimiters to whatever you want, <%= %> is just the default.
Compiled template is essentially htmljs notation Meteor uses (or so I suppose) and it uses Template.template_name.lookup to render correct data. Check in console if Template.template_name.lookup("data_helper")() returns the correct data.
I recently had to solve this exact (or similar) problem of compiling templates client side. You need to make sure the order of things is like this:
Compiled template is present on client
Template data is present (verify with Template.template_name.lookup("data_name")() )
Render the template on page now
To compile the template, as #apendua have suggested, use (this is how I use it and it works for me)
Template.__define__(name, eval(Spacebars.compile(
newHtml, {
isTemplate: true,
sourceName: 'Template "' + name + '"'
}
)));
After this you need to make sure the data you want to render in template is available before you actually render the template on page. This is what I use for rendering template on page:
UI.DomRange.insert(UI.render(Template.template_name).dom, document.body);
Although my use case for rendering templates client side is somewhat different (my task was to live update the changed template overriding meteor's hot code push), but this worked best among different methods of rendering the template.
You can check my very early stage package which does this here: https://github.com/channikhabra/meteor-live-update/blob/master/js/live-update.js
I am fairly new to real-world programming so my code might be ugly, but may be it'll give you some pointers to solve your problem. (If you find me doing something stupid in there, or see something which is better done some other way, please feel free to drop a comment. That's the only way I get feedback for improvement as I am new and essentially code alone sitting in my dark corner).

ASP.net MVC Routing resources

I just cant get this to work...
I have the following routes:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("*.html|js|css|gif|jpg|jpeg|png|swf");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default", // Route name
"{lama}/{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index", lama = "en-gb" } // Parameter defaults
);
And once I load the page.. I have a img element that tries to retrive the following url:
css/img/backgrounds/slide1_2048x1280.jpg
But the image wont show up and if I check my console I get the following error:
GET {my localhost}/cn/Home/css/img/backgrounds/slide1_2048x1280.jpg 404 (Not Found)
I have such a hard time understanding the route-system.. is there anywhere I can read ALOT more about this?.. And could somebody please help me with this single problem then that whould be very appreciated!
I think have fallen foul of relative urls in your html.
Since you haven't said whether this is Razor or Aspx; I'm just going to go with Aspx.
When you write the img tag it seems that you might be doing:
<img src="[relative_path_to_file]" />, using the path of the img relative to the page.
If that doesn't start with / then it's almost certainly the case that you will end up with issues, especially since MVC URLs don't map to the path of the actual page.
What you want to do is to use Url.Content("~/[full_path_to_file]") which will ensure that an absolute path will always be used.
On another note - you really do not need to write all these ignore routes for files that exist on disk. By default, the routing engine will not route existing files - you have to set routes.RouteExistingFiles = true in the RegisterRoutes method in your global in order to route files that already exist; so I think you should get rid of them.
i usually hit up 1) stackoverflow (obviously!), and 2) the msdn docs are pretty good:
http://msdn.microsoft.com/en-us/library/dd410120.aspx. But i usually end up googling for specifically what i need =)
However, looks like you're trying to setup a route to ignore certain filetypes?
i found this article that gives some good ideas on how to handle this.
I've only blocked one or two filetypes before, and i made one line per filetype. Not sure if you can make one line that has extensions delimited by pipe (|) like you're doing (i could be wrong!)
routes.IgnoreRoute("{*allaspx}", new {allaspx=#".*\.aspx(/.*)?"});
routes.IgnoreRoute("{*allswf}", new {allswf=#".*\.swf(/.*)?"});

Resources