django-ecommerce-project-v2's People
Forkers
ty1cube luiz158 nomsynonso eng-yuri89 ga352491 nkoech123 mayals ricnmc20 anarcypher frenzyharmony paulohsneto amontaser meaton-dev21 cforcross kimhan1113 davej61 setiawankarnata muzammilpeer bigbearframersedge isaacky yannickeboo dragos2yo amroyasser hkrhasan parthbhande yunusemretosun uncutgems przemo-git saif-11bit ann-wangui voodooley narravabrion lookinfuture zaynhamza renjithvs chemax911 gmatolo nguyenlongnhat238 sorooshdaryabari hyx0908 maarufb alexisdevgrp boakyeni owami abiaessienrepos muktar11 andreanvictor6374 juliauzbemb turalhasanov11 ashu1click arjunsharma1234 abrorjondev ferronrsmith davidrm901503 kirillmelanich xtrialandtestdjango-ecommerce-project-v2's Issues
could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
Hello, i have this issue when I try to connect elasticsearch with postgres vie docker. This error pop up when I rebuild the container after adding elasticseasrch to docker-compose which is this:
version: '3.8'
services:
web:
build: .
command: gunicorn config.wsgi -b 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
depends_on:
# - db
- pgdb_ecommerce
- search
environment:
- "DJANGO_SECRET_KEY=t8wrj!=x&em6+x%z1_!m6n8m3$$jis8!wkhxzn##!_(-%-u9t2t"
- "DJANGO_DEBUG=True"
- "DJANGO_SECURE_SSL_REDIRECT=False"
- "DJANGO_SECURE_HSTS_SECONDS=0"
- "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False"
- "DJANGO_SECURE_HSTS_PRELOAD=False"
- "DJANGO_SESSION_COOKIE_SECURE=False"
- "DJANGO_CSRF_COOKIE_SECURE=False"
- USE_S3=false
# db:
# image: postgres:11
# volumes:
# - postgres_data:/var/lib/postgresql/data/
# environment:
# - "POSTGRES_HOST_AUTH_METHOD=trust"
pgdb:
container_name: pgdb_ecommerce
image: postgres
restart: always
ports:
- 5432:5432
environment:
- POSTGRES_DB=ecommerce
- POSTGRES_USER=ecommerce
- POSTGRES_PASSWORD=password
esearch:
container_name: search
image: elasticsearch:7.14.2
environment:
- discovery.type=single-node
ports:
- "9200:9200"
volumes:
postgres_data:
I used to run a db before,but after running
docker-compose exec web python manage.py search_index --build
I got this error
elasticsearch.exceptions.ConnectionError:
ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f10cfc2b9d0>:
Failed to establish a new connection: [Errno 111] Connection refused) caused by:
NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f10cfc2b9d0>:
Failed to establish a new connection: [Errno 111] Connection refused)
which is I guess the same issue, bc can't connect them right?
so I change the db to pgdb as yours to see where is the problem but got the same error again
these are my files I guess you need to see
ecommmerce.search.views.py
from django.http import HttpResponse
from elasticsearch_dsl import Q
from rest_framework.views import APIView
from rest_framework.pagination import LimitOffsetPagination
from search.documents import ProductInventoryDocument
from drf.serializer import ProductInventorySerializer
# Create your views here.
class SearchProductInventory(APIView, LimitOffsetPagination):
productinventory_serializer = ProductInventorySerializer
search_document = ProductInventoryDocument
def get(self, request, query):
try:
q = Q(
"multi_match",
query=query,
fields=[
"sku",
],
)
search = self.search_document.search().query(q)
response = search.execute()
results = self.paginate_queryset(response, request, view=self)
serializer = self.productinventory_serializer(results, many=True)
return self.get_paginated_response(serializer.data)
except Exception as e:
return HttpResponse(e, status=500)
ecommerce.search.documents.py
from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry
from inventory.models import ProductInventory, Product
@registry.register_document
class ProductInventoryDocument(Document):
product = fields.ObjectField(properties={"name": fields.TextField()})
class Index:
name = "productinventory"
class Django:
model = ProductInventory
fields = [
"id",
"sku",
"store_price",
"is_default",
]
ecommece.urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from search.views import SearchProductInventory
from drf.views import *
router = routers.DefaultRouter()
router.register(
r"api",
AllProductsViewSet,
basename="allproducts",
)
router.register(
r"product/(?P<slug>[^/.]+)",
ProductByCategory,
basename="Products",
)
urlpatterns = [
# Djago admin
path("bingo/", admin.site.urls),
# User management
path("accounts/", include("allauth.urls")),
# Local apps
path("", include("dashboard.urls")),
path("books/", include("books.urls")),
path("order/", include("order.urls")),
path("checkout/", include("checkout.urls")),
path("api_home/", include(router.urls)),
path("search/<str:query>", SearchProductInventory.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path("__debug__", include(debug_toolbar.urls)),
] + urlpatterns
i add these lines to my settings
INSTALLED_APPS = [
....
....
'django_elasticsearch_dsl',
'rest_framework',
'inventory',
'drf',
'search',
'demo',
'dashboard',
# all the other apps you added to, from the previous parts
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "ecommerce", #I made this database with this user and pass and can find it with pgadmin and it works fine with load-fixtures command
"USER": "ecommerce",
"PASSWORD": "password",
"HOST": "127.0.0.1",
"PORT": "5432",
}
}
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 10,
}
ELASTICSEARCH_DSL = {
"default": {"hosts": "localhost:9200"},
}
I guess these are some extra info maybe it helps
now I'm at part 6 from this tuts,
and when I run this command
curl -X GET localhost:9200/_cluster/health
it works fine
{"cluster_name":"docker-cluster","status":"green","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"active_primary_shards":1,"active_shards":1,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":0,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":100.0}
if you need any more info about my other files , just asked , thanks in advance .
ValidationError on datetime format in mydata.json
Executing the test suite with the fixtures provided by the file part-2/mydata.json
throws the following exception:
E django.core.exceptions.ValidationError: ['โ14:18.33โ value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
runtimeerror: Database access not allowed, when test_promotino_price_reduction run
Hi Zander,
I got this error when I run pytest
RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
FAILED promotion/tests/test_promotion_management.py::test_promotion_price_reduction[10-90]
FAILED promotion/tests/test_promotion_management.py::test_promotion_price_reduction[50-50]
all the other tests passed
accounts/tests/test_account.py .... [ 26%]
dninja/tests/test_all_category.py . [ 33%]
dninja/tests/test_product.py . [ 40%]
drf/tests/test_all_category.py . [ 46%]
drf/tests/test_product.py .. [ 60%]
inventory/tests/test_category.py .. [ 73%]
inventory/tests/test_products.py . [ 80%]
promotion/tests/test_promotion.py . [ 86%]
promotion/tests/test_promotion_management.py ...FF [100%]
when i used db
mark on the test_promotion_price_reduction
it told me the connection already closed! I didn't understand the problem, so if you figure out the reason I'll be glad if you can explain it to me,
bc as I understood the idea which is if we passed promotion_multi_variant
on the task, so the db
mark should pass too
these are my files
test_promotion_management.py
from datetime import date, timedelta
import pytest
from promotion.models import Promotion
from promotion.tasks import promotion_management, promotion_prices
@pytest.mark.parametrize(
"start, end, expected",
[
(date.today(), date.today() + timedelta(5), True),
(date.today() - timedelta(10), date.today() - timedelta(5), False),
(date.today() + timedelta(5), date.today() + timedelta(10), False),
],
)
def test_promotion_management(
start, end, expected, celery_app, celery_worker, promotion_multi_variant
):
promotion_multi_variant.promo_start = start
promotion_multi_variant.promo_end = end
promotion_multi_variant.save(update_fields=["promo_start", "promo_end"])
promotion_management()
promotion = Promotion.objects.all().first()
assert promotion.is_active == expected
@pytest.mark.parametrize(
"reduction, result",
[
(10, 90),
(50, 50),
],
)
def test_promotion_price_reduction(
reduction,
result,
celery_app,
celery_worker,
promotion_multi_variant,
):
promotion_prices(reduction, promotion_multi_variant.id)
new_price = Promotion.products_on_promotion.through.objects.get(
promotion_id=promotion_multi_variant.id
)
assert new_price.promo_price == result
celery.py
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
app = Celery("config")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
task.py
from datetime import datetime
from decimal import Decimal
from math import ceil
from celery import shared_task
from django.db import transaction
from .models import Promotion
@shared_task()
def promotion_prices(reduction_amount, obj_id):
with transaction.atomic():
promotions = Promotion.products_on_promotion.through.objects.filter(
promotion_id=obj_id
)
reduction = reduction_amount / 100
for promo in promotions:
if promo.price_override == False:
store_price = promo.product_inventory_id.store_price
new_price = ceil(store_price - (store_price * Decimal(reduction)))
promo.promo_price = Decimal(new_price)
promo.save()
@shared_task()
def promotion_management():
with transaction.atomic():
promotions = Promotion.objects.filter(is_schedule=True)
now = datetime.now().date()
for promo in promotions:
if promo.is_schedule:
if promo.promo_end < now:
promo.is_active = False
promo.is_schedule = False
else:
if promo.promo_start <= now:
promo.is_active = True
else:
promo.is_active = False
promo.save()
tests.promotion_fixtures.py
import pytest
from datetime import date, timedelta
from promotion.models import *
@pytest.fixture
def single_promotion_type(db):
promotion_type = PromoType.objects.create(name="default")
return promotion_type
@pytest.fixture
def coupon(db):
coupon = Coupon.objects.create(
name="default",
coupon_code="123456789",
)
return coupon
@pytest.fixture
def promotion_multi_variant(
db, single_sub_product_with_media_and_attributes, single_promotion_type, coupon
):
promotion = Promotion.objects.create(
name="Default",
promo_reduction=50,
is_active=False,
is_schedule=True,
promo_type=single_promotion_type,
coupon=coupon,
promo_start=date.today(),
promo_end=date.today() + timedelta(5),
)
single_sub_product = single_sub_product_with_media_and_attributes
promotion.products_on_promotion.add(
single_sub_product["inventory"],
through_defaults={"promo_price": "100.00"},
)
return promotion
settings.py
CELERY_BROKER_URL = "redis://redis:6379"
CELERY_RESULT_BACKEND = "redis://redis:6379"
if there a file you want to see let me know,
thanks in advance
could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
Hello, i have this issue when I try to connect elasticsearch with postgres vie docker. This error pop up when I rebuild the container after adding elasticseasrch to docker-compose which is this:
version: '3.8'
services:
web:
build: .
command: gunicorn config.wsgi -b 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
depends_on:
# - db
- pgdb_ecommerce
- search
environment:
- "DJANGO_SECRET_KEY=t8wrj!=x&em6+x%z1_!m6n8m3$$jis8!wkhxzn##!_(-%-u9t2t"
- "DJANGO_DEBUG=True"
- "DJANGO_SECURE_SSL_REDIRECT=False"
- "DJANGO_SECURE_HSTS_SECONDS=0"
- "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False"
- "DJANGO_SECURE_HSTS_PRELOAD=False"
- "DJANGO_SESSION_COOKIE_SECURE=False"
- "DJANGO_CSRF_COOKIE_SECURE=False"
- USE_S3=false
# db:
# image: postgres:11
# volumes:
# - postgres_data:/var/lib/postgresql/data/
# environment:
# - "POSTGRES_HOST_AUTH_METHOD=trust"
pgdb:
container_name: pgdb_ecommerce
image: postgres
restart: always
ports:
- 5432:5432
environment:
- POSTGRES_DB=ecommerce
- POSTGRES_USER=ecommerce
- POSTGRES_PASSWORD=password
esearch:
container_name: search
image: elasticsearch:7.14.2
environment:
- discovery.type=single-node
ports:
- "9200:9200"
volumes:
postgres_data:
I used to run a db before,but after running
docker-compose exec web python manage.py search_index --build
I got this error
elasticsearch.exceptions.ConnectionError:
ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f10cfc2b9d0>:
Failed to establish a new connection: [Errno 111] Connection refused) caused by:
NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f10cfc2b9d0>:
Failed to establish a new connection: [Errno 111] Connection refused)
which is I guess the same issue, bc can't connect them right?
so I change the db to pgdb as yours to see where is the problem but got the same error again
these are my files I guess you need to see
ecommmerce.search.views.py
from django.http import HttpResponse
from elasticsearch_dsl import Q
from rest_framework.views import APIView
from rest_framework.pagination import LimitOffsetPagination
from search.documents import ProductInventoryDocument
from drf.serializer import ProductInventorySerializer
# Create your views here.
class SearchProductInventory(APIView, LimitOffsetPagination):
productinventory_serializer = ProductInventorySerializer
search_document = ProductInventoryDocument
def get(self, request, query):
try:
q = Q(
"multi_match",
query=query,
fields=[
"sku",
],
)
search = self.search_document.search().query(q)
response = search.execute()
results = self.paginate_queryset(response, request, view=self)
serializer = self.productinventory_serializer(results, many=True)
return self.get_paginated_response(serializer.data)
except Exception as e:
return HttpResponse(e, status=500)
ecommerce.search.documents.py
from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry
from inventory.models import ProductInventory, Product
@registry.register_document
class ProductInventoryDocument(Document):
product = fields.ObjectField(properties={"name": fields.TextField()})
class Index:
name = "productinventory"
class Django:
model = ProductInventory
fields = [
"id",
"sku",
"store_price",
"is_default",
]
ecommece.urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from search.views import SearchProductInventory
from drf.views import *
router = routers.DefaultRouter()
router.register(
r"api",
AllProductsViewSet,
basename="allproducts",
)
router.register(
r"product/(?P<slug>[^/.]+)",
ProductByCategory,
basename="Products",
)
urlpatterns = [
# Djago admin
path("bingo/", admin.site.urls),
# User management
path("accounts/", include("allauth.urls")),
# Local apps
path("", include("dashboard.urls")),
path("books/", include("books.urls")),
path("order/", include("order.urls")),
path("checkout/", include("checkout.urls")),
path("api_home/", include(router.urls)),
path("search/<str:query>", SearchProductInventory.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path("__debug__", include(debug_toolbar.urls)),
] + urlpatterns
i add these lines to my settings
INSTALLED_APPS = [
....
....
'django_elasticsearch_dsl',
'rest_framework',
'inventory',
'drf',
'search',
'demo',
'dashboard',
# all the other apps you added to, from the previous parts
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "ecommerce", #I made this database with this user and pass and can find it with pgadmin and it works fine with load-fixtures command
"USER": "ecommerce",
"PASSWORD": "password",
"HOST": "127.0.0.1",
"PORT": "5432",
}
}
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 10,
}
ELASTICSEARCH_DSL = {
"default": {"hosts": "localhost:9200"},
}
I guess these are some extra info maybe it helps
now I'm at part 6 from this tuts,
and when I run this command
curl -X GET localhost:9200/_cluster/health
it works fine
{"cluster_name":"docker-cluster","status":"green","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"active_primary_shards":1,"active_shards":1,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":0,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":100.0}
if you need any more info about my other files , just asked , thanks in advance .
Inventory tests override each other
Hi,
I've notices that inventory tests in the file test_db_fixtures override each other. Probably, the name of the function in line 349 should be "test_inventory_db_product_attribute_value_dataset"
Unable to make a inventory_product_category link table from part-2
For some reason which I don't know I am unable to see and create the 'inventory_product_category' table in the database.
So that's why I fail in 2 tests (screenshots of the terminal below).
-
I fail in the 'test_inventory_db_product_insert_data' test in the 'assert result_product_category == 5' part where the categories should be 5 but as the 'inventory_product_category' table is not created it does not query properly and shows "result_product_category == 0"
-
Secondly, I fail in the "test_inventory_db_product_dbfixture" test as I am unable to query the product model in models.py from inventory. For this one, I am not sure where I am failing but I guess it's directly related to the 'inventory_product_category' table.
I have cross-checked all my code from the Github repo so I am pretty sure that there are no code issues. I have also provided the notepad copy of the terminal.
Please help me as I am unable to progress in the course
Terminal Copy of Code.txt
where are all the tests gone?
there was a lot of db tests , now when I try to test them a lot of them failed or gave me some errors, before publish my errors and how can I fix them, I want to ask if there will be a new video about testing the hole database again or it will not be necessary , and these few new tests are enough? ( which are work fine without any problems)
Problem installing fixtures: insert or update on table "inventory_productinventory" violates foreign key constraint
hello, sir.
I tried to test my db
after ending part 9 of this tut
with this test
@pytest.mark.dbfixture
@pytest.mark.parametrize(
"id, name, slug, is_active",
[
(1, "fashion", "fashion", 1),
# (2, "woman", "woman", 1),
# (3, "shoes", "shoes", 1),
],
)
def test_inventory_category_dbfixture(db, db_fixture_setup, id, name, slug, is_active):
result = Category.objects.get(id=id)
assert result.name == name
assert result.slug == slug
assert result.is_active == is_active
and this is my db_fixtur_setupe.py
@pytest.fixture(scope="session")
def db_fixture_setup(django_db_setup, django_db_blocker):
"""
Load DB data fixtures
"""
with django_db_blocker.unblock():
call_command("loaddata", "db_product_inventory_fixture.json")
call_command("loaddata", "db_type_fixture.json")
call_command("loaddata", "db_product_attribute_fixture.json")
call_command("loaddata", "db_product_fixture.json")
call_command("loaddata", "db_category_fixture.json")
call_command("loaddata", "db_brand_fixture.json")
call_command("loaddata", "db_product_attribute_value_fixture.json")
call_command("loaddata", "db_media_fixture.json")
call_command("loaddata", "db_stock_fixture.json")
call_command("loaddata", "db_product_attribute_values_fixture.json")
# call_command("loaddata", "db_product_type_attribute_fixture.json")
this is the first Item in db_product_inventory.json
[
{
"model": "inventory.productinventory",
"id": "1",
"fields": {
"sku": "7633969397",
"upc": "100000000001",
"product_type": "1",
"product": "1",
"brand": "1",
"is_active": "1",
"is_default": "1",
"retail_price": "97",
"store_price": "92",
"is_digital": "False",
"weight": "987",
"created_at": "2021-09-01T13:20:30+03:00",
"updated_at": "2021-09-01T13:20:30+03:00"
}
},
]
and when I ran the test i got this error
django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "inventory_productinventory" violates foreign key constraint "inventory_productinv_product_type_id_fa69a5b2_fk_inventory"
E DETAIL: Key (product_type_id)=(1) is not present in table "inventory_producttype".
i have a product_type fixture in db_type_fixture.json
[
{
"model": "inventory.producttype",
"id": "1",
"fields": {
"name": "shoes"
}
}
]
so what is the problem here? pls if you know any info about this,
i googled it and they say: it tried to add the item before its table are build , so I guess in my case
i tried to find the product_type_id=1
in product_inventory
table before I have the product_type
table in my database !
I tried to load db_type_fixture.json
befor db_product_inventory_fixture.json
and still the same error,
I tried to deleted this line call_command("loaddata", "db_type_fixture.json")
and got the same error
so I guess this line doesn't work or there something else with this line
call_command("loaddata", "db_product_inventory_fixture.json")
connection to server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "postgres"
Hey, I cannot connect to Postgres DB running on docker. Actually, I copied all the code and then also I am unable to connect to Postgres.
It always throws me an error saying "password authentication failed" could you please resolve this for me.
I think that Postgres might be hashing the password.
Thanks In advance.
Fixtures Missing
I'm working along with Part-4 however, there is only one fixture. We need the rest of the data to follow along.
Unsupported config option for services: 'pgdb'
Hi Zander,
I seriously doubt this is an issue with your code but I'm just reaching out for some assistance. I've read countless web pages regarding this problem I'm having but none have been able to solve it.
I have been struggling with docker for a few days now. Installation on linux is far from "simple" and there are version and dependency issues, depending on the linux distro one is using.
Using the docker-compose.yml script in your github repo, I get the following:-
ERROR: Version in "./docker-compose.yaml" is unsupported. You might be seeing this error because you're using the wrong Compose file version. Either specify a supported version (e.g "2.2" or "3.3") and place your service definitions under the
services
key, or omit theversion
key and place your service definitions at the root of the file to use version 1.
For more on the Compose file format versions, see https://docs.docker.com/compose/compose-file/
According to what I have read, Version is now deprecated, so I commented out the Version line, but this throws another error:-
ERROR: The Compose file './docker-compose.yaml' is invalid because:
Unsupported config option for services: 'pgdb`
Installing the docker desktop is easier but I think it also still has problems as a part of it is not functioning. It is also still in beta. If I can't get this going, then I will have to resort to installing and using postgres or mysql on the OS as usual.
The yaml script I am using is exactly the same as yours and I am not posting it below as it is a waste of time. The reason being is that adding code using ctrl-e as above results in all the tabs and whitespace being removed. Why? I don't know, but it is not a browser problem, and it isn't me, I don't think.
Dave
NotFoundError(404, 'index_not_found_exception', 'no such index [productinventory]', productinventory, index_or_alias)
now I'm at part 9 , and before adding more codes , i just merged my branches and try to see if everything works before move on ,
my DRF and ninja work fine without any problem, but when I tried to navigate to http://127.0.0.1:8000/api/search/widstar/
i got this error
NotFoundError(404, 'index_not_found_exception', 'no such index [productinventory]', productinventory, index_or_alias)
and these are my files , i think it related to the problem, just for notice it was work fine before, (at the end of part 7 as I remembered )
serach/documents.py
from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry
from inventory.models import ProductInventory
@registry.register_document
class ProductInventoryDocument(Document):
product = fields.ObjectField(
properties={"name": fields.TextField(), "web_id": fields.TextField()}
)
brand = fields.ObjectField(properties={"name": fields.TextField()})
class Index:
name = "productinventory"
class Django:
model = ProductInventory
fields = [
"id",
"sku",
"store_price",
"is_default",
]
search/views.py
from django.http import HttpResponse
from drf.serializer import ProductInventorySearchSerializer
from search.documents import ProductInventoryDocument
from elasticsearch_dsl import Q
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.views import APIView
class SearchProductInventory(APIView, LimitOffsetPagination):
productinventory_serializer = ProductInventorySearchSerializer
search_document = ProductInventoryDocument
def get(self, request, query=None):
try:
q = Q(
"multi_match",
query=query,
fields=["product.name", "product.web_id", "brand.name"],
fuzziness="auto",
) & Q(
should=[
Q("match", is_default=True),
],
minimum_should_match=1,
)
search = self.search_document.search().query(q)
response = search.execute()
results = self.paginate_queryset(response, request, view=self)
serializer = self.productinventory_serializer(results, many=True)
return self.get_paginated_response(serializer.data)
except Exception as e:
return HttpResponse(e, status=500)
config/urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from drf.views import *
from search.views import SearchProductInventory
urlpatterns = [
# Djago admin
# User management
path("accounts/", include("allauth.urls")),
# Local apps
path("", include("dashboard.urls")),
path("books/", include("books.urls")),
path("order/", include("order.urls")),
path("checkout/", include("checkout.urls")),
# API endponts
path("api/inventory/category/all/", CategoryList.as_view()),
path("api/inventory/products/category/<str:query>/", ProductByCategory.as_view()),
path("api/inventory/<int:query>/", ProductInventoryByWebId.as_view()),
# ealsticsearch
path("api/search/<str:query>/", SearchProductInventory.as_view()),
path("ninja/", include("dninja.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path("__debug__", include(debug_toolbar.urls)),
] + urlpatterns
parts from settings.py
INSTALLED_APPS = [
"rest_framework",
"django_elasticsearch_dsl",
"ninja",
# Local
"accounts",
"pages",
"books",
"order",
"checkout",
# New apps for updateing database
"dashboard",
"inventory",
"demo",
# new apps for DRF
"drf",
"search",
"dninja",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "ecommerce",
"USER": "ecommerce",
"PASSWORD": "password",
"HOST": "db",
"PORT": "5432",
"TEST": {
"NAME": "testdatabase",
},
}
}
ELASTICSEARCH_DSL = {
"default": {
"hosts": "esearch",
}
}
dokcer-compose.yml
version: '3.8'
services:
web:
restart: always
container_name: web
build: .
command: gunicorn config.wsgi -b 0.0.0.0:8000
volumes:
- .:/usr/src/app
ports:
- "8000:8000"
depends_on:
- db
- redis
image: app:djnago
environment:
- "DJANGO_SECRET_KEY=t8wrj!=x&em6+x%z1_!m6n8m3$$jis8!wkhxzn##!_(-%-u9t2t"
- "DJANGO_DEBUG=True"
- "DJANGO_SECURE_SSL_REDIRECT=False"
- "DJANGO_SECURE_HSTS_SECONDS=0"
- "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False"
- "DJANGO_SECURE_HSTS_PRELOAD=False"
- "DJANGO_SESSION_COOKIE_SECURE=False"
- "DJANGO_CSRF_COOKIE_SECURE=False"
- USE_S3=false
db:
image: postgres:14
container_name: db
restart: always
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
- "POSTGRES_HOST_AUTH_METHOD=trust"
- POSTGRES_DB=ecommerce
- POSTGRES_USER=ecommerce
- POSTGRES_PASSWORD=password
ports:
- "5432:5432"
esearch:
container_name: esearch
image: elasticsearch:7.14.2
environment:
- cluster.name=ecommerce-elasticsearch
- discovery.type=single-node
- bootstrap.memory_lock=true
- ES_JAVA_OPTS=-Xms128m -Xmx128m
ports:
- "9200:9200"
volumes:
- ./elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml
depends_on:
- db
redis:
container_name: redis
restart: always
image: redis:alpine
ports:
- "6379:6379"
volumes:
postgres_data:
esearch:
Dockerfile
#Pull base image
FROM python
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /usr/src/app
# Install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt
# Copy project
COPY . /usr/src/app/
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.