Magento communicating with another system - web-services

I'm building a magento (1.9CE) store which needs to interface with another system and I could use some guidance.
Although not particularly relevant, I'm communicating with the 'other' system using web services (it's on another server) but what I need help with is finding the places where I need to put in code to do what I want.
There are three major functions that I need to implement:-
When a user clicks on the product detail page I need to make a call to check the stock levels on the other system, update the magento stock levels and THEN display the product detail page.
When a sale is completed, I need to send details of that sale to the other system.
When a new product is added I need to communicate with the other system. This may be a bit more complex because there are a few checks I need to do during the 'add product' process, for example, check the SKU is valid, that tghe product doesn't already exists, etc. I think until I start coding this I shan't realise the full extent of this functionality!
Any guidance gratefully received!

Even though this might (and probably will) dramatically slow down your store, if you want real-time information, I guess the easiest way would be with observers.
You can use catalog_controller_product_init_before: This will trigger when the product detail page is starting loading, so you should be able to upload the stock at this point, before the page has finished loading, so that if there is no stock it will not be buyable, which I guess that's what you want.
You can use sales_order_place_after: This will be triggered after a new order has been placed and saved in the database.
You can use catalog_product_new_action or catalog_product_save_after: Depending on how you create your products the first one might not be triggered. The second one will always be triggered once a product (new or existing) has been saved, so at this point you will need to check if the product is new or existing, and do your stuff depending on that.
For an example of how to create an extension and usage of observer events, check this out.
I hope it helps!

Related

Best Practice Using Django Signal (For user authentication?)

I am new to Django and want to know deeper about the concept of signals.
I know how it works but really don't understand when should one really use it.
From the doc it says 'They’re especially useful when many pieces of code may be interested in the same events.'
What are some real applications that use signals for its advantage?
e.x. I'm trying to make a phone verification after user signup. Because it can be integrated inside the single app and the event that interested for the signal is only this 'verify' function, therefore I don't really need signal. I can just pass the information from one view to the other, rather than using pre_save signal from the registration.
I'm sorry if my question is kind of basic. But I really want to know some insight what is the real application, in which many codes interested in one particular event and what are some trade off in my application.
Thanks!!
Often signals is used when you need to do some database-specific low-level stuff. For example, if you use ElasticSearch for better searching documents on your site, you may want to automatically update search indexes, when new document is created or old one was edited.
Also you may have some complex logic of managing database objects. For example, you may need some specific logic of deleting object. For example, when user is deleted, you may want change all the links to his profile by some placeholder, or when new message is created or other action is performed by user, you want to update "last visited" field in user's profile and there's no direct relation between this action and updating the profile.
But when you're just implementing business-logic as in your example with verification, you don't need to use signals, because you don't need any universal logic related to deleting/creating/editing any object: you have a certain object with which you work and can do stuff directly.

django-channels: keeping track of users in "rooms"

TL;DR - How do I maintain a list of users in each room so that I can send that data to the front-end to display a list of participants in this room.
I'm designing a collaborative web application that uses django-channels for websocket communication between the browser and the server. A room can be joined by more than one user and every user should be aware of every other user in the room. How would I go about achieving this using django-channels (v2)?
I already went through the documentation and a few example projects available online but none of them have added a similar functionality. I also know about django-channels-presence but the project doesn't seem to be actively maintained so I didn't really bother looking into examples using that.
Here's what I've come up with so far:
- For every room, I create an object in the database and those objects can keep track of the users that are in the room. So for e.g in the WS consumer's connect() method I could do a get_or_create_room() call and room.add_participant(self.user_name) (or fetch this from the scope) and in the disconnect() method I could remove myself from the room. The problem with this, however, is that I might end up creating race conditions? I think? Also since I'm fetching objects from the ORM, I have to make sure that every time, before using this object I have to re-fetch it from the DB because it can (and will) become outdated quickly. This doesn't seem ideal at all.
- Another way I can think of is attaching data to self.channel_layer in the consumer where I can do something like setattr(self.channel_layer, f'users_{room_id}', {}) and maintain this dictionary for every user entering and leaving. This again doesn't sound very safe and I didn't see anyone using this so I'm unsure.
Any help regarding this would be appreciated. I'd also like to be able to see how existing applications do this if anyone can point me to one?
so in short there is no way to ask channels for the members in a group so you either need to:
Write some info into the db, with a timestamp so that you can see if it is old
or
send a message every (n seconds) over the channel group (machine readable item with the users id) then your consumers (or frontend) can maintain a list of users and filter this to those that have a resent timestamp. The disadvantage here is it might take a few seconds to detect all the users in a chat room.
You can't do anything like writing to a dict or global object since this is not shared over all the consumers.

How to remove saved responses from a field in Flask-WTForms for patient privacy?

I built an app for work that keeps track of client medications.
Although of course I did not include any client data when I deployed the app in order to be able to demonstrate it to employers, in the dropdown fields you can still see the initials of the clients.
I'm putting it in maintenance mode in between showing it, and I also added a bunch of fake records so that you can only see the real initials mixed in with other random initials (and again, only under the fields in the automatically generated dropdown menus, not in the actual data saved to the database). Since there's no other information about the clients, I think that's pretty much all I really need to do.
But all of this begs a more programmatic solution: how do I edit the previous values that Flask-WTF remembers so that you cannot see them in the dropdown?
Here is what I mean:
Please let me know what options I have!
Thank you.

how continuously run function on page request

I want to use third party's REST API providing real-time foreign exchange rates in my django app which should continuously show changing exchange rates.
my code works but only on every page reload. but I want my code to be running continuously and showing exchange rate on page even if the page is not reloaded.
def example(request)
RATE__API_URL = 'REST API url'
while True
rate = requests.get(RATE__API_URL).json()
b = rate['rates']['EURUSD']['rate']
context = {'b': b}
return render(request, 'example.html', context)
on my example.html
<h1>
{{b}}
</h1>
code is running and does not show any errors
There are a few ways you can solve your requirement and none of them are the "right way", also much of it depends of what you have in your code, so I'll try to lay them out for you, and given the extent of what needs to be done while providing some links so you can work on it, but I will not give code because you'll require a fair amount of tailored code (sorry for that) and the references are good enough for you to develop your own solution.
The first thing you have to keep in mind is than you'll need to solve two really big and really different requirements:
The first part of your solution is retrieving the data from the source in a timely manner. The second part is to have a way to update the data in the template without the need for the user to reload the page.
To retrieve the data you said you already have an API where you'll get the data, but your code is not an efficient way to approach this, and it also may generate a risk because it is prone to hit too many times the API server; the best way I can think of would be if the API has webhooks or push notifications to which you can subscribe (which I doubt), the second best choice is to implement a Celery task, that way you will be calling the data regularly, and you'll not eat the API service resources.
With the first part out of the way, what you have left to do is to implement a way to call regularly from the UI for the newest data. Perhaps the simplest way to solve it is to implement an asynchronous call with Javascript/JQuery embedded in a script inside your template, but remember:
For this to work you'll need a model to store the data (If you don't
have an use for historic data, then just keep the most recent
one).
You'll need a view that exposes the data to your UI call (one that sends a JSON)
Another solution is to implement websockets, and the best way to achieve this for Django is using django-channels. You'll have to implement two main things:
In the backed you need to define the consumers flow so you can send
the data to the UI.
In the template you need to implement the websocket connection and a way to handle the updating part of the data for the user.
If you choose this way, and given than you don't need historic data, you can obviate the model and go straight from the Celery task to the UI through the consumer.

django: routing users through a complex app with class-based views

I'm an advanced beginner at django and python. I'm writing an app to handle registration and abstract submission for a conference, and I'm trying to use class-based views. Users get an emailed link that includes their registration code in the url. Starting at this url, users move through a series of views that collect all the necessary info.
The complication comes from the fact that users often stop half way through, and then want to complete the process several days or weeks later. This means that they might continue from the current page, or they might just click that original link. In addition, after several weeks they might have missed certain deadlines, so, e.g., they can no longer submit an abstract (but they can still register). Along the way, they have checked or unchecked various options that also influence the path they should take through the app.
My question is: where is the best place to put the logic that determines if the user is currently allowed to view that page, and if not, the best url to redirect them too? I thought I would create a custom view class that, e.g., overrides the dispatch method to include global checks (e.g., is conference registration open?), and then subclasses could add additional checks (e.g., has the user entered all the necessary info for her abstract?). The problem I ran into was that the checks were run in the wrong order (I want base class checks run first). I then started investigating custom view decorators or custom middleware. At this point I realized I could use some expert advice about which approach to take. (If it matters, I am not using the django authentication system.) Thanks in advance.
Maybe the form wizard could help you managing the viewing sequence.
In general django greybeards advocate keeping row-wise logic in Models, and table-wise logic in Managers, so it seems appropriate to keep complex view logic in a master view class.
The wizard class can help maintain the order of the views, but to resume an out-dated session you may need to do some model saves (which could get too complex very quickly) or some cookie handling.
In the past, when presented with a similar situation, I took the simplest route and separated user registration and the task that the user wants to perform (event registration). The user registers once but if they fluff up the event registration, they just have to log back in at a later date and do it again (their hassle - not yours!).